// VM namespace
if(typeof VM == 'undefined') {
	var VM = {};
}

/**
 * Form Helper Class
 * 
 * TODO: 	This is a very hacky class which is mainly for example text. 
 * 			but will need to refactor to become extensible 	
 */
VM.Form = Class.create({
	initialize: function(container, options) {
		this.options = Object.extend({
		}, options);
		
		this.container = $(container);
		
		this.textInputs = [];
	},
	
	exampleText: function() {
		this.container.select('form input[type=text]').each( function( inputElem, i) { 
			this.textInputs.push( {
				id: 		inputElem.identify(),
				elem:		inputElem,
				sampleText:	inputElem.value,
				formId:		inputElem.up('form').identify()
			});
			
			inputElem.observe('focus', function(event) {
				var elem = Event.element(event);
				if (elem.value == this.textInputs[i].sampleText) {
					elem.removeClassName('form-dimmed');
					elem.value = '';
				}
			}.bind(this));

			inputElem.observe('blur', function(event) {
				var elem = Event.element(event);
				if (elem.value == '') { 
					elem.addClassName('form-dimmed');
					elem.value = this.textInputs[i].sampleText;
				}
			}.bind(this));
			
		}.bind(this));
	}
});

/**
 * Cookie Helper Class
 */
VM.Cookie = Class.create({
	initialize: function(options){
		this.options = Object.extend({
			defaultDays:	360,
			cookieName:		'vmhp-key'
		}, options);
		
		this.registry = [];
		
		var registryStr = this.get(this.options.cookieName);
		if ( registryStr != null) {
			registryStr = decodeURIComponent(registryStr);
			registryStr.split('|').each( function(cookieName) {
				if (cookieName != '') {
					this.registry.push(cookieName);
				}
			}.bind(this));
		}
	},
	
	add: function(name, value, days) {	
		if (!days) {
			days = this.options.defaultDays;
		}
		
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
		
		document.cookie = name+"="+encodeURIComponent(value)+expires+"; path=/";
		
		this.addToRegistry(name);
	},
	
	get: function(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return decodeURIComponent(c.substring(nameEQ.length,c.length));
		}
		return null;
	},
	
	remove: function(name) {
		this.add(name," ",-1);
		
		this.removeFromRegistry(name);
	},
	
	addToRegistry: function(name) {
		if (name != this.options.cookieName && this.registry.indexOf(name) < 0) {
			this.registry.push(name);
			
			var string = '';
			this.registry.each( function(cookieName) {
					string += cookieName + '|';
			});
			
			this.add(this.options.cookieName, string);
		}
	},
	
	removeFromRegistry: function(name) {
		var cookieKey = null;

		if (cookieKey != null) 
			this.cookies.splice(this.registry.indexOf(name));
	},
	
	empty: function() {
		this.registry.each( function(cookieName) {
			this.remove(cookieName);
		}.bind(this));
		this.remove(this.options.cookieName);
	}
});
var cookieUtility = new VM.Cookie();


/**
 * Dialog Overlay Class
 * 
 */
VM.DialogOverlay = Class.create({
	/**
	 * Initialize the Dialog Overlay 
	 */
	initialize: function(content, container){
		// Manage arguments and assign defaults, 
		if (typeof container == 'undefined' ) container = document.body;
		if (null == (this.container = $(container))) throw("container is not valid");
	
		// Assign instance variables
		this.content = content;
		var pageHeight = document.body.offsetHeight;
		this.overlay = $('hp-overlay') || new Element('div', { 
			id: 'hp-overlay', 
			'style' : 'height:'+pageHeight+'px'
		}).hide();
		this.dialog = $('hp-dialog') ||  new Element('div', { id: 'hp-dialog' }).hide();
	
		// Hide the overlay when clicked. Ignore clicks on the dialog.
		Event.observe(this.overlay, 'click', this.hide.bindAsEventListener(this));
		Event.observe(this.dialog, 'click',  function(event) { Event.stop(event); });
		
		// Insert the elements into the DOM
		this.dialog.insert(this.content);
		this.container.insert(this.overlay);
		this.container.insert(this.dialog);
	
		// Content may have been hidden if it is embedded in the page
		content.show();
		this.dialog.hide();
	},
	
	show: function(){
		new Effect.Appear(this.overlay, { 
			duration: 0.5,  to: 0.8,
			afterFinish: function() {
				var top = Math.round( (document.viewport.getHeight() - this.dialog.getHeight()) / 2 );
				var left = Math.round( (document.viewport.getWidth() - this.dialog.getWidth()) / 2 );
				
				this.dialog.setStyle({
					top:top + 'px',
					left: left + 'px'
				});
				
				this.dialog.show();
			}.bind(this)
		});
		
		return this;
	},
	
	hide: function() {
		this.dialog.hide();
		this.overlay.hide();
		return this;
	}
});


/**
 * Load JS Function
 * Runs all functions/scripts that are in the middle of the page but need 
 * to run after the page finish loading prototype and others script. 
 */
VM.loadScripts = function() {
	if (typeof VM.scripts != 'undefined') {
		var body = document.getElementsByTagName('body')[0];         

		VM.scripts.sort( function(a, b) {
			if (typeof a.priority == 'undefined' && typeof b.priority == 'undefined')
				return 0;
			if ((b.priority == true && typeof a.priority == 'undefined') || 
					(b.priority == true && a.priority == false) )
				return 1;
			if ((a.priority == true && typeof b.priority == 'undefined') || 
					(a.priority == true && b.priority == false) )
				return -1;
			return 0;
		});
		
		VM.scripts.each( function( scriptObj ) {
			var scriptTag = new Element('script', {
				'type':	'text/javascript',
				'src' : scriptObj.src
			});			
			$(body).insert( { 'bottom' : scriptTag } );			
			
			if (Prototype.Browser.IE) {
				//Attach Callbacks to the on load event of the script
				//Thx to IE this check exists...
				scriptTag.observe('readystatechange', function(event) {
					if(scriptTag.readyState == "loaded") {
						runScriptCallbacks();
					}
				});
			} else {
				scriptTag.observe('load',runScriptCallbacks);
			}

			function runScriptCallbacks() {
				var scriptCallback = scriptObj.scriptCallback;
				if (typeof scriptCallback == 'undefined' || scriptCallback == '') {
					return;
				}
				if (typeof scriptCallback == 'function') {
					scriptCallback();
				}
			}
		});
	}
};
Event.observe(window, 'load', VM.loadScripts);

/**
 * RunOnLoadCallback Function
 * Runs all functions/scripts that are in the middle of the page but need 
 * to run after the page finish loading prototype and others script. 
 */
VM.runOnLoadCallback = function() {
	if (typeof VM.onLoadCallbacks != 'undefined') {
		VM.onLoadCallbacks.each( function(callback) {
			callback();
		});
	}
};
Event.observe(window, 'load', VM.runOnLoadCallback);


/*
	CRIR - Checkbox & Radio Input Replacement
	Author: Chris Erwin (me[at]chriserwin.com)
	www.chriserwin.com/scripts/crir/
	
	Updated July 27, 2006.
	Jesse Gavin added the AddEvent function to initialize
	the script. He also converted the script to JSON format.
	
	Updated July 30, 2006.
	Added the ability to tab to elements and use the spacebar
	to check the input element. This bit of functionality was
	based on a tip from Adam Burmister.
	
	Modified January 30, 2009.
	Andrew Martin altered classnames to adhere to
	VirginMedia.com naming conventions
	
	Modified Feb 10, 2009.
	Richard Wong change the logic in init() to allow dynamic 
	checking of the checkbox state
*/
crir = {
	init: function() {
		arrLabels = document.getElementsByTagName('label');
	
		searchLabels:
		for (var i=0; i<arrLabels.length; i++) {			
			// get the input element based on the for attribute of the label tag
			if (arrLabels[i].getAttributeNode('for') && arrLabels[i].getAttributeNode('for').value !== '') {
				labelElementFor = arrLabels[i].getAttributeNode('for').value;				
				inputElement = document.getElementById(labelElementFor);
			}
			else {				
				continue searchLabels;
			}	
			
			if (inputElement !== null && inputElement.getAttributeNode('type') !== null) {
				inputElementType = inputElement.getAttributeNode('type').value;	
				inputElementClass = inputElement.className;	
			} else {
				continue;
			}
	
			// if the input is specified to be hidden intiate it
			if (inputElementClass == 'VM-crirHiddenJS') {
				inputElement.className = 'VM-crirHidden';
	
				// add the appropriate event listener to the input element
				if (inputElementType == "checkbox") {
					inputElement.onclick = crir.toggleCheckboxLabel;
				}
				else {
					inputElement.onclick = crir.toggleRadioLabel;
				}
			}
			// this so even if a radio is not hidden but belongs to a group of hidden radios it will still work.
			else if (inputElement.nodeName != 'SELECT' && inputElement.getAttributeNode('type').value == 'radio') { 
				arrLabels[i].onclick = crir.toggleRadioLabel;
				inputElement.onclick = crir.toggleRadioLabel;
			}
			
			if (inputElementClass == 'VM-crirHidden') {
				// set the initial label state
				if (inputElement.checked) {
					if (inputElementType == 'checkbox') { arrLabels[i].className = 'VM-checkbox-checked'}
					else { arrLabels[i].className = 'VM-radio-checked'; }
				}
				else {
					if (inputElementType == 'checkbox') { arrLabels[i].className = 'VM-checkbox-unchecked'}
					else { arrLabels[i].className = 'VM-radio-unchecked'; }
				}
			}
		}			
	},	
	
	findLabel: function (inputElementID) {
		arrLabels = document.getElementsByTagName('label');
	
		searchLoop:
		for (var i=0; i<arrLabels.length; i++) {
			if (arrLabels[i].getAttributeNode('for') && arrLabels[i].getAttributeNode('for').value == inputElementID) {				
				return arrLabels[i];
				break searchLoop;				
			}
		}		
	},	
	
	toggleCheckboxLabel: function () {
		labelElement = crir.findLabel(this.getAttributeNode('id').value);
	
		if(labelElement.className == 'VM-checkbox-checked') {
			labelElement.className = "VM-checkbox-unchecked";
		}
		else {
			labelElement.className = "VM-checkbox-checked";
		}
	},	
	
	toggleRadioLabel: function () {			 
		clickedLabelElement = crir.findLabel(this.getAttributeNode('id').value);
		
		clickedInputElement = this;
		clickedInputElementName = clickedInputElement.getAttributeNode('name').value;
		
		arrInputs = document.getElementsByTagName('input');
	
		// uncheck (label class) all radios in the same group
		for (var i=0; i<arrInputs.length; i++) {			
			inputElementType = arrInputs[i].getAttributeNode('type').value;
			if (inputElementType == 'radio') {
				inputElementName = arrInputs[i].getAttributeNode('name').value;
				inputElementClass = arrInputs[i].className;
				// find radio buttons with the same 'name' as the one we've changed and have a class of chkHidden
				// and then set them to unchecked
				if (inputElementName == clickedInputElementName && inputElementClass == 'VM-crirHidden') {				
					inputElementID = arrInputs[i].getAttributeNode('id').value;
					labelElement = crir.findLabel(inputElementID);
					labelElement.className = 'VM-radio-unchecked';
				}
			}
		}
	
		// if the radio clicked is hidden set the label to checked
		if (clickedInputElement.className == 'VM-crirHidden') {
			clickedLabelElement.className = 'VM-radio-checked';
		}
	}
};
crir.init();



/* @author:Damien W J King
   @copyright:Virgin Media
   @lastUpdated:16/7/07
   @description: function for outputting embed/object tags for i.e. issue with active x.
   @attibutes: please call with following - divID,codebase,width,height,id,align,movie,quality,bgcolor,wmode in this order as first 8 params.
   anything after this should be "paramName","paramValue" followed in pairs.
   @Function call example 
   <div id="flashContainer"></div>
	<script language="JavaScript" type="text/javascript">
	embedFlash("flashContainer","http://active.macromedia.com/flash2/cabs/swflash.cab#version=4,0,0,0","600","440","main","middle","http://www.virgin.net/cards/ecards.swf","high","#339999","Transperant","salign","T","swLiveConnect","TRUE");
	</script>
	<noscript>This page requires Javascript to be enabled and Macromedia Flash to be installed.</noscript>
	
   @Note: Removed some attributes like quality, seem to be causing type mismatch in ie6.
   
   @have added check flash version so you can use supportedVersion var to decided if to display or not.
   also if you have multiple flash containers on one page please name the flashContainer1, flashContainer2 etc and have the alternative non flash content in
   nonFlash1, nonFlash2 etc.  Make sure they all have a class to hide them initally.  Once the check has been done it will show the relevant divs, ie, either flash content or nonflash.
*/


var w3c=(document.getElementById)? true: false;
var ie5=(w3c && document.all)? true : false;
var ns6=(w3c && (navigator.appName=="Netscape" || navigator.appName=="Opera"))? true: false;
var saf=(navigator.userAgent.indexOf('Safari')!=-1);

var flashversion = 0;
  
function checkFlashVersion() {

  if (navigator.plugins && navigator.plugins.length) {    
    x = navigator.plugins["Shockwave Flash"];
    if (x) {
      if (x.description) {
        y = x.description;
  			flashversion = y.charAt(y.indexOf('.')-1);
  		}
    } 
    else {
      flashversion = 0;
    } 
    
    if (navigator.plugins["Shockwave Flash 2.0"]) {
  		flashversion = 2;
  	}
  }
  else if (navigator.mimeTypes && navigator.mimeTypes.length)
  {
  	x = navigator.mimeTypes['application/x-shockwave-flash'];
  	if (x && x.enabledPlugin)
  		flashversion = 'unknown';
  	else
  		flashversion = 0;
  }
  else {
    testIEFlashVersion();    
  }
  return flashversion;
}
  
function testIEFlashVersion() {
 for(var i=11; i>0; i--){
  		flashversion = 0;
  		try{
  			var flash = new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + i);
  			flashversion = i;
  			return;
  		}
  		catch(e){
  		}
  	}
}

function embedFlash() {
		
	// standard flash attributes
	var classid = "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000";
	var type = "application/x-shockwave-flash";
	var pluginspage="http://www.macromedia.com/go/getflashplayer";
	var allowScriptAccess = "sameDomain";
		
	// get extra paramaters
	var DivID = arguments[0];
	var codebase = arguments[1];
	var width = arguments[2];
	var height = arguments[3];
	var id = arguments[4];
	var align = arguments[5];
	var movie = arguments[6];
	var quality = arguments[7];
	var bgcolor = arguments[8];
	var wmode = arguments[9];
	
	var obj = document.createElement('object');
	var div = document.getElementById(DivID);
	var img = document.createElement('image');
	
	var flashDetected = isFlashReady();

	if(flashDetected) {
		// append object
		if(!saf) {
			div.appendChild(obj);
		}	
		// set object attributes
		obj.setAttribute('width',width);
		obj.setAttribute('height',height);
		obj.setAttribute('align',align);
		obj.setAttribute('id',id);
		obj.setAttribute('codebase',codebase);
		obj.setAttribute('classid',classid);
		obj.setAttribute('bgcolor',bgcolor);
		obj.setAttribute('wmode',wmode);
		
		// reset params - ie 7 compatable yippy
		obj.movie = movie;
		//obj.quality = quality;
		//obj.allowScriptAccess = allowScriptAccess;
		
		// set embed for mozilla 
		var embed = document.createElement('embed');
		embed.setAttribute('src',movie);
		embed.setAttribute('bgcolor',bgcolor);
		embed.setAttribute('name',id);
		embed.setAttribute('type',type);
		embed.setAttribute('pluginspage',pluginspage);
		embed.setAttribute('width',width);
		embed.setAttribute('height',height);
		embed.setAttribute('wmode',wmode);
		
		// arrays for extra params
		xparams = new Array;
		xembed = new Array;

		if(arguments.length > 10 ) {
			i = 10;
			p = 0;
			while(i<arguments.length) {
				eval('obj.'+arguments[i]+'="'+arguments[i+1]+'";');
				embed.setAttribute(arguments[i],arguments[i+1]);
				i=i+2;
				p++;
			}
		}
		if(ns6)div.appendChild(embed); // added to fix ie jscript error
	} else {
		// no flash installed
		div.innerHTML = '<p class="TxtMed">This page requires Macromedia Flash to be installed</p>';
		div.innerHTML += '<p><a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" target="_blank"><img src="../www.virgin.net/pix/getFlash.gif" width="89" height="31" border="0" alt="Download Macromedia Flash"/></a></p>';
	}
}

//Flash Detection

function isFlashReady() {
	 var MM_FlashCanPlay = false;
	 var detected = false; 
     var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;
     if(plugin) {
          detected = true;
     } else if (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0 && (navigator.appVersion.indexOf("Win") != -1)) {				   
		// IE flash detection.
		var detected = ieDetection();

	 }
	 return detected;
}

function ieDetection() {
	for(var i=0; i<10; i++){
		flashVersion = 0;
		try{
			var flash = new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + i);
			flashVersion = i;
			return true;
		}
		catch(e){
		}
		
	}
}

// onload check if version supported show alternative content
// check if flash is right version
var supportedVersion = 8;

var totalDivsArray = new Array;
var flashDivsArray = new Array;

function getDivs() {

	flashVersion = checkFlashVersion();
	// check if version supported
	if(flashVersion<supportedVersion) {
		// show all nonFlash
		showFlash = false;
	} else {
		// show all flash
		showFlash = true;
	}
	// get all divs	
	totalDivsArray = document.getElementsByTagName('div');
  	// loop through all divs check for flashContainer and nonFlash show the correct ones
  	for (i=0;i<totalDivsArray.length;i++) {
		flashId = totalDivsArray[i].id;
		var flashDivName = flashId.search(/flashContainer/);
		var nonFlashDivName = flashId.search(/nonFlash/);
		
		if(flashDivName==0) {
			//found flash div
			var flashDiv = document.getElementById(flashId);
			if(showFlash==true) {
				flashDiv.style.display = "block";
			}
		}
		if(nonFlashDivName==0) {
			//found nonflash div
			var nonFlashDiv = document.getElementById(flashId);
			if(showFlash==false) {
				flashDiv.style.display = "none";
				nonFlashDiv.style.display = "block";
			}
		}
  	} 
}

Event.observe(window, 'load', getDivs);	

























