/* ################ Global variables ################  */
var whichVid , tl = false, monthName = ["January","February","March","April","May","June","July","August","September","October","November","December"], navTimer, WT = {}, DCS = {};

/* ################ Flash Embed ################  */
/** 
 * flashembed 0.31. Adobe Flash embedding script
 * 
 * http://flowplayer.org/tools/flash-embed.html
 *
 * Copyright (c) 2008 Tero Piirainen (tipiirai@gmail.com)
 *
 * Released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * >> Basically you can do anything you want but leave this header as is <<
 *
 * version 0.01 - 03/11/2008 
 * version 0.31 - Tue Jul 22 2008 06:30:34 GMT+0200 (GMT+02:00)
 *
 * modified - Thu Oct 22 2008 15:23:00 GMT+0100 (GMT+00:00)
 * modified by Steve Pugh (spugh@visitlondon.com)
 * output Microsoft or standards compliant <object> element based on browser, remove output of <embed> element
 * output flashvars as URL encoded strings rather than quoted strings
*/
function flashembed(root, userParams, flashvars) {	
	
	function getHTML() {
		
		var html = "";
		if (typeof flashvars == 'function') { flashvars = flashvars(); }

			html = '<object ';
			if ($.browser.msie) {
				html += 'codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" ';			
				html += 'classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ';
				if (!params.id) {
					params.id = "_" + ("" + Math.random()).substring(5);
				}
			} else {
				html += ' type="application/x-shockwave-flash" ';
				html += ' data="'+ params.src +'" ';
			}
			html += 'width="' + params.width + '" height="' + params.height + '"'; 
			if (params.id) {html += ' id="' + params.id + '"';} 
			html += '>';  
			
			if ($.browser.msie) {
				html += '\n\t<param name="movie" value="'+ params.src +'" />';
			}
			
			params.id = params.src = params.width = params.height = null;
			
			for (var k in params) {
				if (params[k] !== null) {
					html += '\n\t<param name="'+ k +'" value="'+ params[k] +'" />';
				}
			}
			if (flashvars) {
				html += '\n\t<param name="flashvars" value="' + concatVars(flashvars) + '" />';
			}
		
			html += "</object>";
			if (debug) { 
				alert(html);
			}
		return html;
	}

	
	function init(name) {
		var timer = setInterval(function() {
			var doc = document;
			var el = doc.getElementById(name); 
			
			if (el) {
				flashembed(el, userParams, flashvars);
				clearInterval(timer); 
				
			} else if (doc && doc.getElementsByTagName && doc.getElementById && doc.body) {
				clearInterval(timer);
			}
		}, 13);
		
		return true;
	}

	
	// override extend params function 
	function extend(to, from) {
		if (from) {
			for (key in from) {
				if (from.hasOwnProperty(key)) {
					to[key] = from[key];
				}
			}
		}
	}		
	
	// setup params
	var params = {
		
		// very common params
		src: '#',
		width: '100%',
		height: '100%',		
		
		// flashembed specific options
		version:null,
		onFail:null,
		expressInstall:null,  
		debug: false,
		
		// flashembed defaults
		bgcolor: '#ffffff',
		allowfullscreen: true,
		allowscriptaccess: 'always',
		quality: 'high',
		type: 'application/x-shockwave-flash',
		pluginspage: 'http://www.adobe.com/go/getflashplayer'
	};
	
	
	if (typeof userParams == 'string') {
		userParams = {src: userParams};	
	}
	
	extend(params, userParams);			 
		
	var version = flashembed.getVersion(); 
	var required = params.version; 
	var express = params.expressInstall;		 
	var debug = params.debug;

	
	if (typeof root == 'string') {  
		var el = document.getElementById(root);
		if (el) {
			root = el;	
		} else {
			return init(root);		
		} 
	}
	
	if (!root) { return; }
	
	
	// is supported 
	if (flashembed.isSupported(required)) {
		params.onFail = params.version = params.expressInstall = params.debug = null; 
		root.innerHTML = getHTML();	
		// return our API			
		return root.firstChild;
	} 
	
	
	function concatVars(vars) {		
		var out = "";
		
		for (var key in vars) { 
			if (vars[key]) {
				out += [key] + '=' + asString(vars[key]) + '&';
			}
		}			
		return out.substring(0, out.length -1);				
	}  
	
	// JSON.asString() function
	function asString(obj) {
		switch (typeOf(obj)){
			case 'array':
				return '['+ map(obj, function(el) {
					return asString(el);
				}).join(',') +']'; 
			case 'function':
				return '"function()"';
			case 'object':
				var str = [];
				for (var prop in obj) {
					if (obj.hasOwnProperty(prop)) {
						str.push('"'+prop+'":'+ asString(obj[prop]));
					}
				}
				return '{'+str.join(',')+'}';
			default: 
				return obj;
		}
		//  remove spaces
		return escape(String(obj).replace(/\s/g, " "));
	}
	
	
	// private functions
	function typeOf(obj) {
		if (obj === null || obj === undefined) { return false; }
		var type = typeof obj;
		return (type == 'object' && obj.push) ? 'array' : type;
	}
	
	
	// version 9 bugfix: (http://blog.deconcept.com/2006/07/28/swfobject-143-released/)
	if (window.attachEvent) {
		window.attachEvent("onbeforeunload", function() {
			__flash_unloadHandler = function() {};
			__flash_savedUnloadHandler = function() {};
		});
	}
	
	function map(arr, func) {
		var newArr = []; 
		for (var i in arr) {
			if (arr.hasOwnProperty(i)) {
				newArr[i] = func(arr[i]);
			}
		}
		return newArr;
	}

	return root;
}



// setup jquery support
if (typeof jQuery == 'function') {
	
	(function($) { 
		$.fn.extend({
			flashembed: function(params, flashvars) {  
				return this.each(function() { 
					flashembed(this, params, flashvars);
				});
			}		
		}); 
	})(jQuery);
}


flashembed = flashembed || {};

// arr[major, minor, fix]
flashembed.getVersion = function() {

	var version = [0, 0];
	
	if (navigator.plugins && typeof navigator.plugins["Shockwave Flash"] == "object") {
		var _d = navigator.plugins["Shockwave Flash"].description;
		if (typeof _d != "undefined") {
			_d = _d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
			var _m = parseInt(_d.replace(/^(.*)\..*$/, "$1"), 10);
			var _r = /r/.test(_d) ? parseInt(_d.replace(/^.*r(.*)$/, "$1"), 10) : 0;
			version = [_m, _r];
		}
		
	} else if (window.ActiveXObject) {
		
		try { // avoid fp 6 crashes
			var _a = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
			
		} catch(e) {
			try { 
				_a = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
				version = [6, 0];
				_a.AllowScriptAccess = "always"; // throws if fp < 6.47 
				
			} catch(ee) {
				if (version[0] == 6) { return; }
			}
			try {
				_a = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			} catch(eee) {
			
			}
			
		}
		
		if (typeof _a == "object") {
			_d = _a.GetVariable("$version"); // bugs in fp 6.21 / 6.23
			if (typeof _d != "undefined") {
				_d = _d.replace(/^\S+\s+(.*)$/, "$1").split(",");
				version = [parseInt(_d[0], 10), parseInt(_d[2], 10)];
			}
		}
	} 
	
	return version;
};


flashembed.isSupported = function(version) {
	var now = flashembed.getVersion();
	var ret = (now[0] > version[0]) || (now[0] == version[0] && now[1] >= version[1]);			
	return ret;
};
/* ################ End Flashemebed ################ */

/* ################ Flash ################ */
function videoMultiTrackWrapper(trackPath,trackTitle,trackEvent) {
	WT.ti=WT.cg_n=WT.cg_s=WT.mc_id=WT.si_n=WT.si_p=""; // null all values we don't use
	dcsMultiTrack("DCS.dcsuri",trackPath,"WT.z_ltvName","Video: "+trackTitle,trackEvent,"1");
	DCS.dcsuri=WT.z_ltvName=WT.z_ltvView=WT.z_ltvPlay=WT.z_ltvFinished=""; // null all values we do use
}

function detectFlash() {};

function drawTV() {
if(whichVid && whichVid !== "" && $("#video").size !== 0) {
var w, h, xml = whichVid + ".xml";
	if ($.browser.msie || $.browser.safari) { w = '540'; h = '352'; } else { w = '240'; h = '184'; }
	$("#video").flashembed({
		src: 		"http://static.visitlondon.com/assets/video/vl-video-player.swf",
		width: 		w, 
		height: 	h,
		play: 		"true",
		wmode: 		"transparent",
		scale: 		"noscale",
		salign: 	"rt",
		version:	[8,0]
	},
	{
		xmltouse: xml,
		PageColour: 'grey'
	});
	if (tl === true) {
			$("#video").append('<a id="transcriptLink" href="http://static.visitlondon.com/assets/video/transcripts/'+whichVid+'.html"><img src="http://static.visitlondon.com/images/icons/transcript.gif" alt="" />read the transcript</a>');
			$("#transcriptLink").css('cursor','pointer').css('display','block').css('margin-top','188px').css('margin-bottom','10px').click(
			function() {
				window.open('http://static.visitlondon.com/assets/video/transcripts/'+whichVid+'.html', 'trans', 'width=550, height=550, location=no, scrollbars=yes');
				return false;
				}
			);
			$("#video").height(200);
		}
		else {	
			$("#video").height(188);
		}
		if ($.browser.safari) {
			$("#video object, #video embed").css('clip','rect(0,540px,184px,300px)');
		}
	}
}

function goBig() {
	if (!$.browser.msie) {
		$("#video object, #video embed").width(540).height(352);
		if ($.browser.safari) {
			$("#video object, #video embed").css('clip','auto'); 
		}
	}
}

function goSmall() {
	if (!$.browser.msie) {
		$("#video object, #video embed").width(240).height(184);
		if ($.browser.safari) {
			$("#video object, #video embed").css('clip','rect(0,540px,184px,300px)');
		}
	}
}
   
function drawMovie(tagID, myMovie, w, h) {
	$("#"+tagID).flashembed({
		src: 		myMovie,
		width: 		w, 
		height: 	h,
		play: 		"true",
		wmode: 		"transparent",
		scale: 		"noscale",
		salign: 	"rt",
		version:	[8,0]
	});
}
/* ################ End Flash ################ */


/* ################  External Links  ################ */
function externalLinks() { 
	var intLink = /^https?\:\/\/[a-z0-9\-]*.?visitlondon\.com/, server = /(web[1234]|preview|vl\-dev\-web1)/;
	$("a[href^='http']").filter(function() {return  !intLink.test($(this).attr("href"));}).filter(function() {return !server.test($(this).attr("href"));}).add("a.ext, a[href$='mp3'], a[href$='pdf'], a[href$='doc']").not(".gallery").attr({title: 'Link will open in a new window', target: '_blank'});
	$("#content a[href^='http']").filter(function() {return !intLink.test($(this).attr("href"));}).filter(function() {return  !server.test($(this).attr("href"));}).add("#content a.ext, #content a[href$='mp3'], #content a[href$='pdf'], #content a[href$='doc']").not(".button").not(".gallery").not(".noicon").append("<img src='http://static.visitlondon.com/images/icons/external-links.gif' alt='' width='16' height='11' />");
}
/* ################  External Links  ################ */


/* ################ Tabs  ################ */
function trackSwitchTabs(el) { 
var tab_title, tab_code, product_name = $("h1:first").text;
	switch (el) {
		case 'prod-desc'       : tab_title="Description"; tab_code = 'Desc'; 	break;	
		case 'prod-map'        : tab_title="Map"; tab_code = 'Map';	    break;	
		case 'prod-contact'    : tab_title="Contact"; tab_code = 'Contact';	break;	
		case 'prod-rooms'      : tab_title="Room Layouts"; tab_code = 'Layout';	    break;	
		default: tab_title="Unknown";
	}
	WT.cg_n=WT.cg_s=WT.mc_id=WT.si_n=WT.si_p=WT.z_vlSupplier="";
	dcsMultiTrack('DCS.dcsuri','/js/showTab/'+tab_title,'WT.ti','Show Tab: '+tab_title , 'WT.z_ltvName', 'Tabs: '+product_name, 'WT.z_ltv'+tab_code, '1');	
	WT.z_ltvDesc=WT.z_ltvMap=WT.z_ltvContact=WT.z_ltvLayout='';
}


function showtab() {
	var theTab = $("#header .current").attr('id').replace('-tab', ''), whichTab="#" + theTab;
		$(whichTab).show();
		trackSwitchTabs(theTab);
}
function setupTabs() {
if($(".tabcnt").size() === 0 || $("#header li a").size === 0) {return false;}
		$(".tabcnt").hide();
		$("#header li a").css('cursor','pointer').click(function(event){
			$(".tabcnt").hide();
			$("#header .current").removeClass('current');
			$(this).parent().addClass('current');
			$(this).blur();		
			showtab();
		return false;});
		showtab();
}
/* ################ End Tabs ################ */




/* ################ Top Nav ################ */
function topmenuClear() {
	var navRoot = document.getElementById("topmenu");
		for (var i=0; i<navRoot.childNodes.length; i++) {
			var node = navRoot.childNodes[i];
			if (node.nodeName=="LI") {
				node.className=node.className.replace("over", "");
				node.childNodes[0].className="";
			}
		}
}
function topmenuHover() {
	if(document.getElementById("topmenu")) {
		var navRoot = document.getElementById("topmenu");
		for (var i=0; i<navRoot.childNodes.length; i++) {
			var node = navRoot.childNodes[i];
			if (node.nodeName=="LI") {
				node.onmouseover=function() {
					clearTimeout(navTimer); topmenuClear();
					this.className+=" over";
					this.childNodes[0].className="over"; 
				};
				node.onmouseout=function() {
					navTimer = setTimeout(topmenuClear,2000);
				};
			}
		}
	}
}
/* ################ End Top Nav ################ */




/* ################ RFP ################ */
function goToPage(p) {
    var toField = document.getElementById("to");    
    switch (p) {
        case 'One' : toField.value = "rfpContactView"; break;
        case 'Two' : toField.value = "rfpEventView"; break;
        case 'Three' : toField.value = "rfpVenueView"; break;
        case 'Four' : toField.value = "rfpAccommodationView"; break;
        case 'Five' : toField.value = "rfpAdditionalView"; break;
    }
    document.forms.theForm.submit();
}

function leapYear (inYear) { if ((inYear % 4 === 0) && ((inYear % 100 !== 0) || (inYear % 400 === 0))) {return true;}}
function getMaxDay(selectedMonth,selectedYear) {
	var maxDay;
	if (selectedMonth == '2') { if (leapYear(selectedYear) ) {maxDay = 29;} else {maxDay = 28;} }  
  	else { if  (selectedMonth == '4' || selectedMonth == '6' || selectedMonth == '9' || selectedMonth == '11') { maxDay = 30;} else { maxDay = 31; } }
  return maxDay;
}
function getMinDay(selectedMonth,selectedYear) {
var now = new Date(), minDay;
	if (selectedMonth == (now.getMonth() + 1) && selectedYear == now.getYear()) { minDay = now.getDate(); }
	else { minDay = 1; }
	return minDay;
}
/* Dates */
function checkMonths(prefix,dftOpt,formName,suffix) {
var esuffix;
	if (!dftOpt || dftOpt === "") { dftOpt = 0; }
	if (!formName || formName === "") { formName = "theForm"; }
	if (suffix && suffix != "") {esuffix = "." + suffix; }
	else {esuffix="";}
	var	f = document.forms[formName];
	var whichYear = f.elements[prefix + ".year"+esuffix];
	var whichMonth = f.elements[prefix + ".month"+esuffix];
	var whichDay =  f.elements[prefix + ".day"+esuffix];

	var selectedDay = whichDay.options[whichDay.selectedIndex].value;
	var selectedMonth = whichMonth.options[whichMonth.selectedIndex].value;
	var selectedYear = whichYear.options[whichYear.selectedIndex].value;
	var maxDay = getMaxDay(selectedMonth,selectedYear);
	var minDay = getMinDay(selectedMonth,selectedYear);
	while (whichDay.length > dftOpt) { whichDay.remove(dftOpt); }
	for (var k = minDay; k <= maxDay; k++) {
		var kpos = k - minDay + dftOpt;
	 	var ksel = false; if (k == selectedDay) { ksel = true; }
     	whichDay.options[kpos] = new Option(k, k, false, ksel);
	}
}



function setDate(formName,idate,oday,omonth,oyear,suffix) {
	var f = document.forms[formName], esuffix, odate,  mi, di, yi, diVal, miVal, yiVal, idateArray;
	if (suffix && suffix != "") { 
		esuffix = "-" + suffix; 
	} else {
		esuffix="";
	}
	odate = idate + '-date' + esuffix;
	idateArray = f.elements[odate].value.split("."); // input should (d)d.mm.yyyy
	for (mi=0; mi < f.elements[omonth].options.length; mi++) {
		if (f.elements[omonth].options[mi].value < 10) {
			miVal = "0" + f.elements[omonth].options[mi].value;
		} else {
			miVal = f.elements[omonth].options[mi].value;
		}
		if (miVal == idateArray[1]) {
			f.elements[omonth].options[mi].selected = true;
		}	
	} 
	
	checkMonths(idate,1,formName,suffix);
	
	for (di=0; di < f.elements[oday].options.length; di++) {
		diVal = f.elements[oday].options[di].value;
		if (diVal == idateArray[0]) {
			f.elements[oday].options[di].selected = true;
		}	
	}

	for (yi=0; yi < f.elements[oyear].options.length; yi++) {
		yiVal = f.elements[oyear].options[yi].value;
		if (yiVal == idateArray[2]) {
			f.elements[oyear].options[yi].selected = true;
		}	
	}
}


function setDropDownDate(cal) {
	var esuffix;
	if (cal.params.suffix) {
		esuffix = "." + cal.params.suffix;
	} else {esuffix = "";}
	var iArray = cal.params.inputField.name.split("-"), oyear = iArray[0] + '.year'+esuffix, omonth = iArray[0] + '.month'+esuffix, oday = iArray[0] + '.day'+esuffix;
	setDate(cal.params.formName,iArray[0],oday,omonth,oyear,cal.params.suffix);
}

/* Disallow dates in the past or prior to start date */
function dateStatusFrom(date) { var	min = new Date(); min.setDate(min.getDate() - 1); if (date.getTime() < min.getTime() ) { return true; }	else { return false; } }


/* ################ End RFP ################ */



/* ################ Maps  ################ */

function zoomMap() {
	var el = document.getElementById('venueMap');
	if (el.src.indexOf('scale=0.5') != -1) { el.src = el.src.replace('scale=0.5', 'scale=1.0');} 
	else { el.src = el.src.replace('scale=1.0','scale=0.5');}
}

function scrollMap(direction) {
	var offsetx = 0, offsety = 0, newURL = "http://maps.visitlondon.com/?", newx, newy, elArray = document.getElementById('venueMap').src.split(/[\?\&]/);
	for (var i = 0; i < elArray.length; i++) {
		if (elArray[i].indexOf('offset-x') != -1 ) {
			offsetx = elArray[i].substring(9);
		} else { 
			if (elArray[i].indexOf('offset-y') != -1 ) {
				offsety = elArray[i].substring(9);
			}
		}
	}
	switch (direction) {
		case 'n'    : newx=offsetx;  newy=+offsety+500;	break;	
		case 'e'    : newx=+offsetx+500;  newy=offsety;	break;	
		case 'w'    : newx=+offsetx-500;  newy=offsety;	    break;	
		case 's'    : newx=offsetx;  newy=+offsety-500;	break;	
		case 'ne'   : newx=+offsetx+500;  newy=+offsety+500;	    break;	
		case 'nw'   : newx=+offsetx-500;  newy=+offsety+500;	    break;	
		case 'se'   : newx=+offsetx+500;  newy=+offsety-500;	    break;
		case 'sw'   : newx=+offsetx-500;  newy=+offsety-500;	    break;					
		default: newx=offsetx;  newy=offsety;
	}
	for (var i = 1; i < elArray.length; i++) {
		if (elArray[i].indexOf('offset-x') == -1 && elArray[i].indexOf('offset-y') == -1 ) {
			newURL+= elArray[i]+'&';
		}
	}
	newURL+= 'offset-x='+newx+'&offset-y='+newy;
	document.getElementById('venueMap').src = newURL;
}
/* ################ End Maps  ################ */

function cleanNum(field) {
  field.value = field.value.replace(/[^0-9]/g, '');
}

function convertArea() {
	var result = '';
	if ($("#area-widget input[name=units]:checked").val() == 'm') {
		result = $("#area-widget input[name=area]").val() * 3.28;
		result = result.toFixed(2);
		result += 'ft\xB2';
	}
	else {
		result = $("#area-widget input[name=area]").val() / 3.28;
		result = result.toFixed(2);
		result += 'm\xB2';
	}
	return result;
}


/* ################ Loader ################ */
	var now = new Date(), message, newBrand = new Date();
	newBrand.setFullYear(2009,8,21);
	
	if (now.getHours() > 18) { message = "Good evening"; }
	else  if (now.getHours() > 12)  {message = "Good afternoon";}
	else  if (now.getHours() > 6)  {message = "Good morning";}
	else {message = "Hello";}

 $(document).ready(function(){
 	setupTabs();   
	externalLinks();
	drawTV();
	$("#topmenu > li").hover(
		function(){ clearTimeout(navTimer); topmenuClear();  $(this).addClass("over");  $(this).find(":first").addClass("over"); },
		function(){  navTimer = setTimeout(topmenuClear,2000); }
	);
	$("img.rollover, input.rollover, a.rollover img").hover(
		function () { var tSrc = $(this).attr('src'); $(this).attr('src', tSrc.replace('-off.', '-on.')); },
		function () { var tSrc = $(this).attr('src'); $(this).attr('src', tSrc.replace('-on.', '-off.')); }	
	);
	$('#message').text(message);
		
	if (document.getElementById("bhpf2")) {
		drawMovie("bhpf2", "http://static.visitlondon.com/business2/flash/business-homepage-video-player.swf?xmltouse=video-playlist-expand-2009.xml",'540', '325')
	}
	
	$("#area-widget").append('Convert: <input type="number" name="area" size="6"/> <input type="radio" value="m" name="units" checked="checked">m&sup2; <input type="radio" value="ft" name="units">ft&sup2; <input type="button" value="" class="button button-submit"/> <strong>&nbsp;</strong>');
	$("#area-widget input:button").click(function() {$("#area-widget strong").text(convertArea())});
 });
