/*********************************************** 
		Javascript for Roxtons
***********************************************/	
document.write('<link rel="StyleSheet" href="/roxtonsAssets/css/roxtonsJavascript.css" type="text/css" media="screen" />');
/******************************************************************************************
Global variables
******************************************************************************************/
var assets = "/roxtonsAssets/";
var ua = navigator.userAgent.toLowerCase();
/******************************************************************************************
set bolean to detect safari on mac - the flash text does not seem to work with 
the opacity background on any gecko browsers on mac
******************************************************************************************/
macNotSafari = (ua.indexOf("windows") == -1)&&(ua.indexOf("safari") == -1)? true:false; 
/******************************************************************************************
Flash detect. boolean true/false if installed and version number accessed via flash.version
******************************************************************************************/
if (navigator.plugins && navigator.plugins.length) {
	for (x=0; x < navigator.plugins.length; x++) {
		if (navigator.plugins[x].name.indexOf('Shockwave Flash') != -1) {
			var flash = new Object();			
			flash.version = eval(navigator.plugins[x].description.split('Shockwave Flash ')[1].split('.')[0]);					
			break;
		}
	}
}
else if (window.ActiveXObject) {
	for (x = 2; x <= 20; x++) {
		try {
			oFlash = eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash." + x + "');");
			if(oFlash) {
				var flash = new Object();				
				flash.version = x;
			}
		}
		catch(e) {}
	}
}
if(flash && !macNotSafari) {
	document.write("<link rel=\"StyleSheet\" href=\""+assets+"/css/roxtonsEnhanced.css\" type=\"text/css\" media=\"screen\" />");
}
/******************************************************************************************
On body load run these configuration functions
@param 		bodyRef 		object reference of the entire body of the page
******************************************************************************************/
function fnInit(bodyRef) {
	fnFRT();
	fnFbFRT();
}
/******************************************************************************************
Find all <h2> tags with class 0f "flashTxt" and replace content with flash movie with "Myriad Roman" font.
Will not run on Firefox Mac.
******************************************************************************************/
function fnFRT() {
	if(flash && !macNotSafari) {
		var topHeadings = document.getElementsByTagName("H2");
		var text, swf;
		
		for (i=0;i<topHeadings.length;i++) {
			if (topHeadings[i].className=="flashTxt") {		//look for class "flashTxt"	
				text 	= escape(topHeadings[i].innerHTML); 	// Grab text and encode
				swf		= fnMakeFlash(assets+"swf/flashTxt.swf?t="+text,270,20);
				topHeadings[i].innerHTML = "<span class=\"hide\">"+topHeadings[i].innerHTML+"</span>"+swf;
				topHeadings[i].style.visibility = "visible";
			}
		}
	}
}


/******************************************************************************************
Find all <h2> tags with class 0f "fbFlashTxt" and replace content with flash movie with "Myriad Roman" font.
Will not run on Firefox Mac.
******************************************************************************************/
function fnFbFRT() {
	if(flash && !macNotSafari) {
		var topHeadings = document.getElementsByTagName("H2");
		var text, swf;
		
		for (i=0;i<topHeadings.length;i++) {
			if (topHeadings[i].className=="fbFlashTxt") {		//look for class "flashTxt"	
				text 	= escape(topHeadings[i].innerHTML); 	// Grab text and encode
				swf		= fnMakeFlash(assets+"swf/fbFlashTxt.swf?t="+text,270,20);
				topHeadings[i].innerHTML = "<span class=\"hide\">"+topHeadings[i].innerHTML+"</span>"+swf;
				topHeadings[i].style.visibility = "visible";
			}
		}
	}
}





/********************************************************************************

Name: 				make flash
Description:		Return 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

*********************************************************************************/

function fnMakeFlash(swf,width,height) {	
	return '<embed src="'+swf+'" menu="false" width="'+width+'" height="'+height+'" type="application/x-shockwave-flash" wmode="transparent" pluginspage="http://www.macromedia.com/go/getflashplayer" />';	
}


/********************************************************************************
 
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";
	}		
}

/* print function */
function fnPrint() {
	window.print();
}

//SETTING UP OUR POPUP
//0 means disabled; 1 means enabled;
var popupStatus = 0;

$(document).ready(function () {
    $(".jsHide").hide();
    $(".jsShow").show();

    //Closing the address popup
    //Click the x event!  
    $("#popupAddressClose").click(function () {
        disableAddressPopup();
    });
    //Click out event!  
    $("#backgroundPopup").click(function () {
        disableAddressPopup();
    });
    //Press Escape event!  
    $(document).keypress(function (e) {
        if (e.keyCode == 27 && popupStatus == 1) {
            disableAddressPopup();
        }
    });
	
    // SDAY - 21/11/2011 - Make tabs only work on venue pages
    // because the other 'tabs' with the same classes aren't
    // actual javascript tabs

    if($("#content > .venue").length > 0) {
	    if (window.location.hash != "") {
	        $(".tabbedContent div").hide();
        	$(window.location.hash).show();
	        $(".tabNavWrapper li").removeClass("selected");
        	$(window.location.hash.replace("#tab", ".aTab")).parent().addClass("selected");
	    }

	    $(".tabNavWrapper a").click(function () {
	        $(".tabbedContent div").hide();
        	window.location.hash = $(this).attr("class").replace("aTab", "tab");
	        $("#" + $(this).attr("class").replace("aTab", "tab")).show();
        	$(".tabNavWrapper li").removeClass("selected");
	        $(this).parent().addClass("selected");
        	return false;
    	});
	
    }

    // 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] = "Australasia";
    regionTitles[3] = "Caribbean";
    regionTitles[4] = "Central & South America";
    regionTitles[5] = "Europe";
    regionTitles[7] = "North America";
    regionTitles[8] = "Indian Sub Continent"; // India
    regionTitles[9] = "Indian Ocean Islands";
    // 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();
    $("#noJSContent .destinationList").each(function () {
        var divId = $(this).attr("id");
        var regionKeys = [divId.substr(divId.indexOf("destinationList") + 15)];
        // force the grouping of north america, asia and australasia into one region
        var regionIncludeKeys = '';
        mapMenus[regionKeys[0]] = getToolTip(regionKeys);
        mapAreas.push({ key: regionKeys[0], includeKeys: regionIncludeKeys });
    });
    // Push on our fake regions too
    mapAreas.push({ key: "Outside", isSelectable: false });
    // 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 altImage = 'roxtonsAssets/images/destinationsMapJSAlternate';
    altImage += ($("#destinationsMapImage").hasClass("fishing")) ? "_fishing" : "_shooting";
    altImage += '.gif';
    var options = {
        fill: false,
        stroke: false,
        altImage: altImage,
        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,
        mapScale:false,
        onMouseover: showToolTip,
        onClick: showToolTip
    };

    $("#destinationsMapImage").mapster(options);
    
    // 2011 Venue enhancements
    $("#contactUsForm form").attr("action", "");
    $('#bookingFormPopup.submitted').show();
    $('#bookingFormPopup').css({ top: '30%', left: '50%', margin: '-' + ($('#bookingFormPopup').height() / 2) + 'px 0 0 -' + ($('#bookingFormPopup').width() / 2) + 'px' });

    // Override the click of the "enquire now" button so that we can
    // popup a form instead of redirecting to a new page
    $(".bookBtn").click(function () {
        $("#bookingFormPopup").show();
        return false;
    });

    // Override the click of the "close x" links on the popup form
    $("#bookingFormPopup a.close").click(function () {
        $("#bookingFormPopup").hide();
        return false;
    });

    // Override the click on the submit button so that we can trigger a Google Analytics event
    $("#bookingForm input#submit").click(function () {
        _gaq.push(['_trackPageview', '/bookNow.aspx?result=submitted']);
    });
    
    // Enable the function of the venue page thumbnails
    $("#venueThumbs .destinationThumb a").click(function () {
        // Swap the big image for the one this link is linked to
        $("#shTarg img").attr("src", this.href);

        // mark the thumbnail containing divs as selected or not so it gets the right css classes
        // for non-canvas browsers and the background image
        $("#venueThumbs .destinationThumb").removeClass("selected").addClass("notSelected");
        $(this).parent().removeClass("notSelected").addClass("selected");

        if (canvasSupport()) {
            // Swap the coloured/normal thumbnails for this image
            // using canvas if the browser supports it
            $(this).children("img").first().src = venueThumbnails[$(this).parent().attr("id")][0];
        }
        // grayscale the others too
        grayscaleNonSelectedVenueThumbs();

        // re-bind the mouseovers
        bindVenueThumbMouseOvers();

        // stop the browser going anywhere
        return false;
    });

    // bind the mouseover actions on ready too
    bindVenueThumbMouseOvers();

  // Enable the cycling of images on the country pages
    $('.countryHeaderImg').cycle({
        fx: 'fade'
    });
});

function showToolTip(data) {
    // 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) {
            data.e.pageX = data.e.pageX + 150;
        }
        $("#mapWrapper .jsContent .mapMenu").position({
            "of": data.e,
            "my": "center top",
            "at": "center top",
            "collision": "none"
        });
        // Called DD_belated to fix pngs in IE6
        if ($.browser.msie && $.browser.version.substr(0, 1) == 6) {
            DD_belatedPNG.fix("#destinationsMapPopup");
        }
    }
}


function getToolTip(regions) {
    var toolTipText = "";
    var toolTip = null;
    if (regions.length > 1) {
        // multiple regions, combine lists...
        for (i = 0; i < regions.length; i++) {
            if (i == 0) {
                toolTip = $("#noJSContent .inner #destinationList" + regions[i] + " ul");
            }
            else {
                toolTip = toolTip.add($("#noJSContent .inner #destinationList" + regions[i] + " ul"));
            }
        }
    }
    else {
        toolTip = $("#noJSContent .inner #destinationList" + regions[0] + " ul");
    }

    // Our toolTip is now a whole load of <li> 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).children("li").each(function () {
        if (itemCount < 8) {
            lists += '<li class="mapPopup">' + $(this).html() + '</li>';
        }
        else if (itemCount == 8) {
            lists += '<li class="mapPopup">' + $(this).html() + '</li>';
            if ($(toolTip).children("li").length > 8) {
                lists += "</ul><ul>";
            }
        }
        else if (itemCount > 8) {
            lists += '<li class="mapPopup">' + $(this).html() + '</li>';
        }
        itemCount++;
    });
    lists += "</ul>";
    var columnClass = ($(toolTip).children("li").length > 8) ? "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>';
    return toolTipText;
}

function postcodeLookup() {
    var options = '';
    var postcode = $("input[id$='postCode']").val();
    if (postcode.length > 0) {
        centerAddressPopup();
        loadAddressPopup();

        $.getJSON("/PostcodeAnywhere.ashx?p=" + postcode.replace(" ", ""), function(data) {
            for (i = 0; i < data.length; i++) {
                options += "<option value=\"" + data[i].id + "\">" + data[i].description + "</option>";
            }
            $("#addressLookup").html(options);
        });
    } else {
        $("[id$='rfvPostcode']").css("display", "inline");
    }
    return false;
}
function selectAddress() {
    var id = $("#addressLookup").val();
    $.getJSON("/postcodeAnywhere.ashx?id=" + id, function(data) {
    $("input[id$='address1']").val((data.Company ? data.Company : data.Address1));
        $("input[id$='address2']").val((data.Company ? data.Address1 : data.Address2));
        $("input[id$='address3']").val((data.Company ? data.Address2 : data.Address3));
        $("input[id$='address4']").val((data.Company ? data.Address3 : data.Address4));
        $("input[id$='townCity']").val(data.City);
        $("input[id$='postCode']").val(data.Postcode);
        $("input[id$='county']").val(data.County);
    });
    disableAddressPopup();
}
function loadAddressPopup() {
    //loads popup only if it is disabled
    if (popupStatus == 0) {
        $("#backgroundPopup").css({
            "opacity": "0.7"
        });
        $("#backgroundPopup").fadeIn("slow");
        $("#popupAddress").fadeIn("slow");
        popupStatus = 1;
    }
}
function disableAddressPopup() {
    //disables popup only if it is enabled
    if (popupStatus == 1) {
        $("#backgroundPopup").fadeOut("slow");
        $("#popupAddress").fadeOut("slow");
        popupStatus = 0;
    }
}
function centerAddressPopup() {
    //request data for centering
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    var popupHeight = $("#popupAddress").height();
    var popupWidth = $("#popupAddress").width();
    //centering
    $("#popupAddress").css({
        "position": "fixed",
        "top": windowHeight / 2 - popupHeight / 2,
        "left": windowWidth / 2 - popupWidth / 2
    });
    //only need force for IE6
    $("#backgroundPopup").css({
        "height": windowHeight
    });
}

$(window).load(function () {
    // Greyscale initial thumbnails
    venueThumbnails = new Array();
    if (canvasSupport()) {
        // We need to save the original image urls, and the grayscale versions
        // in a global variable so that we can swap them over at will
        // in other functions
        $("#venueThumbs .destinationThumb a img").each(function () {
            venueThumbnails[$(this).parent().parent().attr("id")] = [this.src, grayscale(this)];
        });
    }
    // Then initialise the non-selected thumbs
    grayscaleNonSelectedVenueThumbs();
});

function bindVenueThumbMouseOvers() {
    // clear original bindings
    $("#venueThumbs .destinationThumb a img").unbind('mouseover').unbind('mouseout');
    //re-bind to not selected images
    $("#venueThumbs .notSelected a img").mouseover(function () {
        $(this).css("filter", "progid:DXImageTransform.Microsoft.BasicImage(grayscale=0)");
        if(canvasSupport()){
            this.src = venueThumbnails[$(this).parent().parent().attr("id")][0];
        }
    }).mouseout(function () {
        $(this).css("filter", "progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)");
        if(canvasSupport()){
            this.src = venueThumbnails[$(this).parent().parent().attr("id")][1]; 
        }
    });
}

function grayscaleNonSelectedVenueThumbs() {
    // Use the global variable to swap over the initial non-selected venue images
    // we only need to do this for canvas images because IE will use it's
    // filter from the .notSelected css
    if (canvasSupport()) {
        $("#venueThumbs .notSelected a img").each(function () {
            this.src = venueThumbnails[$(this).parent().parent().attr("id")][1];
        });
    }
}

// Function to grayscale an image using HTML5 canvas
// This function actually draws a canvas with a grayscaled representation of the supplied image in it
// and returns a url you can use to display it
function grayscale(imgObj) {
    var canvas = document.createElement('canvas');
    var canvasContext = canvas.getContext('2d');
    var imgW = imgObj.width;
    var imgH = imgObj.height;

    canvas.width = imgW;
    canvas.height = imgH;
    canvasContext.drawImage(imgObj, 0, 0);

    var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH);

    for(var y = 0; y < imgPixels.height; y++){
         for(var x = 0; x < imgPixels.width; x++){
              var i = (y * 4) * imgPixels.width + x * 4;
              var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
              imgPixels.data[i] = avg;
              imgPixels.data[i + 1] = avg;
              imgPixels.data[i + 2] = avg;
         }
    }
    canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);

    return canvas.toDataURL();
}

// Function to check for canvas support
function canvasSupport() {
    canvas_compatible = false;
    try {
        canvas_compatible = !!(document.createElement('canvas').getContext('2d')); // S60
    } catch (e) {
        canvas_compatible = !!(document.createElement('canvas').getContext); // IE
    }
    return canvas_compatible;
}


