document.write('<link rel="StyleSheet" href="/baileyRobinsonAssets/css/baileyRobinsonJavascript.css" type="text/css" media="screen" />');

/********************************************************************************
 
Name:     fnConfig
Function: main configuration function. sets up all functions to be called onLoad
 
*********************************************************************************/

function fnConfig() {
	fnSetDefaultSelected();
}

/********************************************************************************
 
Name:     jQuery
Function: jQuery on DOM ready function
 
*********************************************************************************/

var tabs = 4;
var count = 1;
var interval = 10;

$(function() {
  fnSearchBox();
  fnOffers();
  fnHomeFeature();
  
  $("#homepage #featureArea").everyTime(interval*500, function(i) {
    fnChangeTab();
  });

});



/********************************************************************************
 
Name:     Flash plugin detect
 
*********************************************************************************/
var flashdetect = false;
function fnFlashDetect() {
 if (navigator.plugins && navigator.plugins.length) {
  for (x=0; x < navigator.plugins.length; x++) {
   if (navigator.plugins[x].name.indexOf('Shockwave Flash') != -1) {
     flashdetect = true;      
    break;
   }
  }
 }
 else if (window.ActiveXObject) {
  for (x = 2; x <= 20; x++) {
   try {
    oFlash = eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash." + x + "');");
    if(oFlash) {
     flashdetect = true;  
    }
   }
   catch(e) {}
  }
 }
}
fnFlashDetect(); // run on file load; 



	
/********************************************************************************
 
Name:     Flash embed
Description:  Writeout flash code. Fixes Eolas update for IE as well.
@param swf  String path to swf file
@param width     Number value of movie width
@param height    Number value of movie height
@param alternateContent String of HTML to be served if flash is not installed
 
*********************************************************************************/
 
flash = new Object();
flash.insert = function(swf,width,height) {
	swf = swf.replace(/\./g,"%2E") // encode periods as %2e	
 if(flashdetect) {
 	flashObject = '<embed src="'+swf+'" menu="false" quality="high" width="'+width+'px" height="'+height+'px" type="application/x-shockwave-flash" wmode="transparent" salign="T" pluginspage="http://www.macromedia.com/go/getflashplayer" />'
 	document.write(flashObject);
 } else {
  	//flashObject = alternateContent;
	fnShowNoFlash();
 }
 
 
}

function fnShowNoFlash() {
	if (document.getElementById("noFlashContent")) {
		document.getElementById("noFlashContent").style.display = "block";
	}
	if (document.getElementById("noFlashContent1")) {
		document.getElementById("noFlashContent1").style.display = "block";
	}
	if (document.getElementById("noFlashContent2")) {
		document.getElementById("noFlashContent2").style.display = "block";
	}
	if (document.getElementById("noFlashContent3")) {
		document.getElementById("noFlashContent3").style.display = "block";
	}
	if (document.getElementById("noFlashContent4")) {
		document.getElementById("noFlashContent4").style.display = "block";
	}		
}



/********************************************************************************
 
Name:     DestinationsShowHide
Description:  Takes link url on thumbnails and shows this image within the page.  
Sets transparency of thumbnails once selected.
@param targ:     path to full size image

*********************************************************************************/

function fnDestinationsShowHide(targ) {

	document.getElementById("headerShowHide").getElementsByTagName("img")[0].src = targ.href;	
	document.getElementById("headerShowHide").getElementsByTagName("img")[0].alt = targ.getElementsByTagName("IMG")[0].alt;	
	
	var anchors = document.getElementById("shThumbnails").getElementsByTagName("A");

	if (document.all) {
		for (i=0;i<anchors.length;i++) {
			targ.parentNode.parentNode.getElementsByTagName("IMG")[i].style.filter = "alpha(opacity=100)";		
			}	
		targ.getElementsByTagName("IMG")[0].style.filter = "alpha(opacity=50)";
		}
	else {
		for (i=0;i<anchors.length;i++) {
			targ.parentNode.parentNode.getElementsByTagName("IMG")[i].style.opacity = "1";			
			}	
		targ.getElementsByTagName("IMG")[0].style.opacity = "0.5";
		}
	}
	


	
/********************************************************************************
 
Name:     		fnSetDefaultSelected
Description: 	Sets the default selected state on itinerary nav on first item 
				in nav list - wont get set for non-js users so they can browse
				the standard anchor list

*********************************************************************************/	

function fnSetDefaultSelected() {
	if(document.getElementById("itineryNavList")) {
		var listItems = document.getElementById("itineryNavList").getElementsByTagName("LI");
		listItems[0].className = "selected";
	}
}
	



/********************************************************************************
 
Name:     		fnSelectMe
Description: 	Sets class "selected" on the LI in the itinerary nav list that is 
				clicked on

*********************************************************************************/	
function fnSelectMe(obj) {
	var listItems = document.getElementById("itineryNavList").getElementsByTagName("LI");
	
	for (i=0;i<listItems.length;i++) {
		listItems[i].className = "";
	}	
	
	obj.parentNode.className = "selected";
}


	
/********************************************************************************
 
Name:     		fnItineraryShowHide
Description: 	Show / Hide the itinerary tabbed content.  Anchor contains link to ID 
				of element to show/hide.  JS tales the url, splits string to get ID 
				after the "#", and uses this ID to target element to show/hide.

*********************************************************************************/	
	
function fnItinerarySH(targ) {
	
	var itDetails = document.getElementById("itDetailWrapper").getElementsByTagName("DIV");
	
	for (i=0;i<itDetails.length;i++) { /* Loop through to hide all items */
		itDetails[i].style.display = "none";	
		}	
	
	var showItem = targ.href.split("#")[1];	/* Get ID from link */
	document.getElementById(showItem).style.display = "block";	
	
	}		
	
	
	

	
/********************************************************************************
 
Name:     fnPopup
 
*********************************************************************************/
function fnPopup(sUrl, scrollbars) {	
	if (!scrollbars) {
		scrollbars = "yes";
	}
	var iWidth = 360;
	var iHeight = 350;
	var sScreenX = screen.width;
	var sScreenY = screen.height;
	var x = sScreenX - iWidth;
	var y = sScreenY - iHeight;
	var winLeft = x/2;
	var winTop =  y/2;	
	window.open(sUrl,"","width=" + iWidth + ",height="+ iHeight + ",scrollbars="+scrollbars+",left=" + winLeft + ",top=" + winTop + ",resizable=yes");	
}


/********************************************************************************
 
Name:     fnPopUpStyle
 
*********************************************************************************/
function fnPopUpStyle(filePath, popUpStyle, attributes) {
	var width = 0;
	var height = 0;
	var sScreenX = screen.width
	var sScreenY = screen.height

	switch (popUpStyle){
		case "1" : 
			width = "600";
			height = "400";
			break;
		case "2":
			width = "412";
			height = "400";
			break;			
		case "3" :
			width = "620";
			height = "420";
			break;
		case "4" :
			width = "420";
			height = "297";
			break;			
		case "5" :
			width = "780";
			height = "540";
			break;			
			
	}

	var x = sScreenX - width
	var y = sScreenY - height
	var winLeft = x/2
	var winTop =  y/2 
	
	
	window.open(filePath,"","width=" + width + ",height=" + height + "," + attributes + ",left=" + winLeft + ",top=" + winTop)

}	



/* print function */
function fnPrint() {
	window.print();	
}

/********************************************************************************
Name:     fnSearchBox
*********************************************************************************/
function fnSearchBox(){
	
	sb = $('#searchForm input:text');
	id = sb.attr('id');
	label = $("#searchForm label[for='"+id+"']");
	
	label.hide();
	sb[0].defaultValue = label.text();
	sb.attr('value',label.text())
	
	sb.unbind("focus,blur").focus(function () {		
		if ($(this).val() == $(this)[0].defaultValue) {
        	$(this).val("");
        }
	 }).blur(function() {
        if ($(this).val() == "") {
        	$(this).val($(this)[0].defaultValue);
     	}
	 });

}

/********************************************************************************
Name:     fnOffers
*********************************************************************************/
function fnOffers(){
	if($('#offersBlock').length>0){
    	block = $('#offersBlock');
		$('div.offerSect',block).each(function(i){
			obj = $(this);
			title = $('div.offerTitle',obj);
			list = $('div.thumbNailList',obj);
			
			if(obj.hasClass('open')){
				list.show();
			} else {
				list.hide();
				obj.addClass('closed');
			}
			
			//setup click
			
			title.bind('click',function(){
				par = $(this).parents('div.offerSect');
				
				if(par.hasClass('closed')){
					//open it
					$(this).next('div.thumbNailList').slideDown();
					par.removeClass('closed').addClass('open');
				}else if(par.hasClass('open')){
					$(this).next('div.thumbNailList').slideUp();
					par.removeClass('open').addClass('closed');
				}
				
			});
			
			
		});	
	}
}

/********************************************************************************
Name:     fnHomeFeature
*********************************************************************************/

function fnHomeFeature(){
	if($('#homepage').length>0){

	    $('#homeTabs a').each(function(i) {
	        obj = $(this);
	        ref = obj.attr('href');
	        ref = ref.slice((ref.length - 4), ref.length);
	        obj.attr('href', ref);
	        obj.click(function() {
	            $('#featureArea').attr('class', '').addClass($(this).attr('href'))
	            $('.fbLatestOffersHome .offer').hide();
	            $('.fbLatestOffersHome .' + $(this).attr('href')).show();
	            $("#homepage #featureArea").stopTime();
	            $("#homepage #featureArea").everyTime(interval * 500, function(i) {
	                fnChangeTab();
	            });
	            return false;
	        })
	    });
		
	}
}



function fnChangeTab(){
	str = 'tab' + count;
	$('#featureArea').attr('class', '').addClass(str);
	$('.fbLatestOffersHome .offer').hide();
	$('.fbLatestOffersHome .' + str).show();
	
	if(count > (tabs-1)){
		count = 1;
	}else{
		count++;
	}

}

// JQuery document.ready()
$(document).ready(function () {
    // Enable the ImageMapster script and setup the map
    // Hide the alternative links
    $("#noJSContent").hide();
    // Insert the popup div container
    $("#mapWrapper .jsContent").prepend('<div class="mapMenu" style="z-index:2000; position:absolute"></div>');
    $("#mapWrapper .jsContent .mapMenu").hide();
    regionTitles = new Array();
    regionTitles[1] = "Africa & Arabia";
    regionTitles[2] = "Antarctica & The Falkland Islands";
    regionTitles[3] = "Australasia";
    regionTitles[4] = "Caribbean";
    regionTitles[5] = "South & Central America";
    regionTitles[6] = "Europe";
    regionTitles[7] = "Indian Ocean Islands";
    regionTitles[8] = "Indian Subcontinent";
    regionTitles[9] = "North America";
    regionTitles[10] = "Far East";
    // Determine which areas should be available to mapster, and build menus for them
    // by looking at what the server has put into the page
    mapAreas = new Array();
    mapMenus = new Array();
    $("#WorldRegions option").not('[value="NONE"]').each(function () {
        // We determine the available areas by looking at the world regions which
        // are present in the document (in a select item)
        var regionKeys = [$(this).attr("value")];
        var regionIncludeKeys = '';
        mapMenus[regionKeys[0]] = getToolTip(regionKeys);
        mapAreas.push({ key: regionKeys[0], includeKeys: regionIncludeKeys, toolTip: ' ', onMouseover: showToolTip });
    });
    // Push on our fake regions too
    mapAreas.push({ key: "Outside", isSelectable: false, onMouseover: showToolTip });
    // And remove the other areas
    $("#destinationsImageMap area").each(function () {
        var divId = $(this).attr("id");
        if (divId.indexOf("Region") != -1) {
            var regionId = divId.substr(divId.indexOf("Region") + 6);
            if (mapMenus[regionId] == null) {
                $(this).remove();
            }
        }
    });
    // Build the popup menus
    var options = {
        fill: false,
        stroke: false,
        altImage: 'baileyRobinsonAssets/images/destinationsMapJSAlternate.gif',
        singleSelect: true,
        toolTipContainer: '<div></div>',
        // we handle tooltips manually, but need to turn them on
        // so that we can hook into their mouseover events
        showToolTip: true,
        mapKey: 'data-mapkey',
        areas: mapAreas
    };

    $("#destinationsMapImage").mapster(options);

});

// Function to show tooltips on image maps
function showToolTip(e, data, mapDataObject) {
    // Hide any shown tooltips unless they're for the same region as we're showing now
    if ($("#destinationsMapPopup").length == 0 || !$("#destinationsMapPopup").is(":visible") || !$("#destinationsMapPopupContent").hasClass("Region" + data.key)) {
        $("#mapWrapper .jsContent .mapMenu").hide();
        // Select the area
        $("#Region" + data.key).mapster('select');
        // Swap the popup's content for the currently selected one
        $("#mapWrapper .jsContent .mapMenu").empty();
        $("#mapWrapper .jsContent .mapMenu").prepend(mapMenus[data.key]);
        // Give the popup content div a class to identify it
        $("#destinationsMapPopupContent").addClass("Region" + data.key);
        // Show the popup
        $("#mapWrapper .jsContent .mapMenu").show();
        // Center it on the mouse
        // IE6 gives us weird values, this fixes it a little bit
        if ($.browser.msie && $.browser.version.substr(0, 1) == 6) {
            //e.pageX = e.pageX + 150;
        }
        $("#mapWrapper .jsContent .mapMenu").position({
            "of": e,
            "my": "left center",
            "at": "right top",
            "collision": "none"
        });
        // Called DD_belated to fix pngs in IE6
        if ($.browser.msie && $.browser.version.substr(0, 1) == 6) {
            DD_belatedPNG.fix("#destinationsMapPopupTop, #destinationsMapPopupContent, #destinationsMapPopupBottom, #mapPopupArrow, .mapPopup, .mapPopup a");
        }
    }
}

// Function to build tooltips on image maps from the html on the current page
function getToolTip(regions) {
    // The HTML is in a series of HTML Select elements
    // We know the id(s) of the world region, so we need to get
    // the id(s) of the countries in that region, and then build 
    // a html list of them
    var toolTipText = "";
    var toolTip = null;
    var countryIds = null;
    //console.log(regions);
    // First we get all the ids of the all countries in the region(s)
    if (regions.length > 1) {
        // multiple regions, combine lists...
        for (i = 0; i < regions.length; i++) {
            if (i == 0) {
                countryIds = $('#WorldRegionsToCountries option[value="' + regions[i] + '"]')
            }
           else {
               countryIds = countryIds.Add($('#WorldRegionsToCountries option[value="' + regions[i] + '"]'));
            }
        }
    }
    else {
        countryIds = $('#WorldRegionsToCountries option[value="' + regions[0] + '"]');
    }
    //console.log(countryIds);
    // Now that we have all the country ids, we can get the names of each of these countries
    $(countryIds).each(function () {
        if (toolTip == null) {
            toolTip = $('#Countries option[value="' + $(this).text() + '"]');
        }
        else {
            toolTip = toolTip.add($('#Countries option[value="' + $(this).text() + '"]'));
        }
    });

    //console.log(toolTip);

    // Our toolTip is now a whole load of <option> elements, which we need to format into
    // some HTML that looks nice and goes into one or two columns, depending on how
    // many items there are.
    var itemCount = 1;
    var lists = "<ul>";
    $(toolTip).each(function () {
        if (itemCount < 10) {
            lists += '<li class="mapPopup"><a href="/country.aspx?CountryId=' + $(this).attr("value") + '">' + $(this).text() + '</a></li>';
        }
        else if (itemCount == 10) {
            lists += '<li class="mapPopup"><a href="/country.aspx?CountryId=' + $(this).attr("value") + '">' + $(this).text() + '</a></li>';
            if ($(toolTip).length > 10) {
                lists += "</ul><ul>";
            }
        }
        else if (itemCount > 10) {
            lists += '<li class="mapPopup"><a href="/country.aspx?CountryId=' + $(this).attr("value") + '">' + $(this).text() + '</a></li>';
        }
        itemCount++;
    });
    lists += "</ul>";
    var columnClass = ($(toolTip).length > 10) ? "doubleColumn" : "singleColumn";
    var toolTipText = '<div id="destinationsMapPopup" class="' + columnClass + '">';
    toolTipText += '<div id="destinationsMapPopupTop"></div>';
    toolTipText += '<div id="destinationsMapPopupContent"><h2>' + regionTitles[regions[0]] + '</h2>' + lists + '<div class="clr"><hr /></div></div>';
    toolTipText += '<div id="destinationsMapPopupBottom"></div>';
    toolTipText += '</div>';

    //console.log(toolTipText);
    return toolTipText;
}
