/*@cc_on 
	@if (@_win32)
		try {document.execCommand('BackgroundImageCache', false, true);}catch(e){}
	@end
	@if (@_jscript_version >= 5.5 && @_jscript_version < 5.7)
			pngfix=function(){var els=document.body.getElementsByTagName("*");var ip=/\.png/i;var i=els.length;while(i-->0){var el=els[i];var es=el.style;if(el.src&&el.src.match(ip)&&!es.filter){es.height=el.height;es.width=el.width;es.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+el.src+"',sizingMethod='crop')";el.src=clear}else{var elb=el.currentStyle.backgroundImage;if(elb.match(ip)){var path=elb.split('"');var rep=(el.currentStyle.backgroundRepeat=="no-repeat")?"crop":"scale";es.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+path[1]+"',sizingMethod='"+rep+"')";es.height=el.clientHeight+"px";es.backgroundImage="none";}}}};
			$(function(){pngfix();});
	@end
@*/
var FC = {
	vars: {
		currencies : /([\£\$\€]{1})/ // add more currencies here with a leading '\' then the currency symbol NOT a unicode or html entity,
	},
	toDecimalString : function (val) {
		__val = Number(val);
		return ((__val * 100) % 100) ? __val.toString() : __val + ".00";
	},
	clearChildren : function (n){
		while (n.firstChild){
			n.removeChild(n.firstChild)
		}
		return n;
	},	
	showChildren : function (el) {
		var __str = "";
	
		for (var __j in el){
			__str += __j +" = "+ el[__j] + ", "
		}
	
		alert(__str);
	},
	addEvent: function(obj, evt, fn) {
		if (obj.addEventListener)
			obj.addEventListener(evt,fn,false);
		 else if (obj.attachEvent)
			obj.attachEvent('on'+evt,fn);
			
		if (obj.getAttribute('href')){
			obj.onclick = function(){
				return false
			}
		} else if (obj.getAttribute('href') && !obj.getAttribute('onclick')){
			var func = obj.onclick;
			obj.onclick = function () {
				func();
				return false;
			}
		}			
	},
	removeEvent: function(obj, type, fn) {
		if (obj.removeEventListener)
			obj.removeEventListener(evt,fn,false);
		else if (obj.detachEvent)
			obj.detachEvent('on'+evt,fn);
	},
	commonEventObject : function (e) {
		var __t;
			
		if (e.target) {
			__t = e.target;
		} else if (e.srcElement) {
			 __t = e.srcElement;
		}
		
		if (__t.nodeType == 3) {// defeat Safari bug
			__t = __t.parentNode;
		}
		
		return __t;
	},
	hideCalendar : function (e, cal) {
		var __returnFalse = false;
		
		if (e.target.className == 'cal-input'){ // if the target is the input field
			__returnFalse = true;
		}
		
		if ($(e.target).parents(".cal-popup").length) { // if the target is a child of the pop-up
			__returnFalse = true;
		}
		
		if ($(e.target)[0].tagName == 'A' && $(e.target).text().indexOf('Month') != -1) { // // if the target is one of the 'Month' buttons on the popup
			__returnFalse = true;
		}
		
		if ($(e.target)[0].className) { // if the target is the 'close-cal' div
			if ($(e.target)[0].className.indexOf("close-cal") != -1) {
				__returnFalse = false;
			}
		}
		
		if ($(e.target).parents(".close-cal").length) { // if the target is a child of the 'close-cal' div
			__returnFalse = false;
		}

		if (__returnFalse) {
			return false;
		}
		
		$('body').unbind("click", function () {FC.hideCalendar()});		
		/*@cc_on @*/ 
			/*@if (@_jscript_version <= 5.7) 
				$('.cal-popup', cal).bgiframe().hide();  
			@else @*/ 
				$('.cal-popup', cal).hide(); 
		/*@end @*/
		return false;
	},
	calendar: function(){
		$.getScript("javascript/jquery-ui-personalized-1.5.3.packed.js", function(){
			/*@cc_on 
				@if (@_jscript_version <= 5.7) 
					$.getScript('javascript/jquery.bgiframe.min.js'); 
				@end 
			@*/
			
			$('.content.calendar').each(function(){
				var theCal = $(this)[0];
				
				function setDates (input) {}
				
				$(".cal-content", theCal).datepicker({ 
					changeMonth: false,
					changeYear: false,
					closeAtTop: false, 
					dateFormat: "dd/mm/yy",
					dayNamesMin: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
					duration: "", 
					firstDay: 1,
					minDate: '0d',
					maxDate: '+2y',
					mandatory: true,
   					nextText: "Next Month",
					numberOfMonths: 2, 
					onSelect: function(date) { 
						$('.cal-input', theCal).val(date);
						$('.cal-popup',theCal).toggle();
    				},
					prevText: "Previous Month", 
					rangeSelect: false
				}).children("div").css({ width : "390px",position:"absolute"});
				
				$('.choose-date').show();
				$('.choose-date',this).css({display:'inline-block',verticalAlign:"middle"});
				$(".choose-date", this).bind("click", function (e) {
					$('body').bind("click", function (e) {FC.hideCalendar(e, theCal)});

					/*@cc_on @*/ 
						/*@if (@_jscript_version <= 5.7) 
							$('.cal-popup', theCal).bgiframe().show();  
						@else @*/ 
							$('.cal-popup', theCal).show(); 
					/*@end @*/	
					
					
					// look for the empty row and set a boolean if the row is completely empt
					// difficult to find a way to discern an empty row
					/*
					$('.ui-datepicker-days-row', theCal).each(function () {
						var __isEmpty = true;
						$('td', this).each(function () {
							if (this.firstChild.nodeValue.search(/[0-9]/) != -1) {
								__isEmpty = false;
							}
						});
						//alert(__isEmpty);
					});
					*/
					
					
					return false; // to stop bubbling
				});
				$(".cal-input", this).bind("focus", function(){
					$('body').bind("click", function (e) {FC.hideCalendar(e, theCal)});
					/*@cc_on @*/ 
						/*@if (@_jscript_version <= 5.7) 
							$('.cal-popup', theCal).bgiframe().toggle();  
						@else @*/ 
						$('.cal-popup', theCal).show(); 
					/*@end @*/	
					return false;
				});
			});
		});
		$('head > link').filter(':first').after('<link rel="stylesheet" type="text/css" href="css/ui.datepicker.css" media="screen" />');
	},
	tooltip : function(){
		$.getScript("javascript/jquery.dimensions.min.js", function(){
			var __topZIndex = Number(1001);
		  	$('.tooltip', 'th').each(function() {
				var time = 200;
				var hideDelay = 200;
				var hideDelayTimer = null;
				var beingShown = false;
				var shown = false;
				
				var trigger = $('img', this);
				var popup = $('.tooltip-wrapper', this).css('opacity', 0);
				
				trigger.bind("mouseover focus", function(e){
					var scrollPos = e.pageY - $(window).scrollTop(), __pos;
					var cssObj = {
						left : (FC.isLteIE7) ? -85 : - 93,
						display: 'block',
						'z-index': __topZIndex++
					};
					
					if (hideDelayTimer) clearTimeout(hideDelayTimer);
					if (scrollPos > 125){
						cssObj.bottom = 25;
						popup.removeClass('flipped');
					} else {
						cssObj.top = 29;
						popup.addClass('flipped');
					}
					if (beingShown || shown) {
						return;
					} else {
						beingShown = true;
						popup.css(cssObj).animate({opacity: 1}, time, 'swing', function() {
							beingShown = false;
							shown = true;
						});
					}
				}).bind("mouseout blur", function(e){
					var scrollPos = e.pageY - $(window).scrollTop();
					if (hideDelayTimer) clearTimeout(hideDelayTimer);
					if (scrollPos > 125){
						var distance = '-=10';
					} else {
						var distance = '+=10';
					}
					hideDelayTimer = setTimeout(function() {
						hideDelayTimer = null;
						popup.animate({opacity: 0}, time, 'swing', function() {
							shown = false;
							$(this).css('display', 'none');
						});
					},
					hideDelay);
				});
			});
		});
	},
	toggleextras : function(){
		var $__root = '.panel';
		$('.details', $__root).each(function() {
			var $__trigger = $(".more-extras", this);
			var $__content = $(".extras table", this).hide();
			$([$__trigger.get(0)]).bind("click", function(){
				$__content.slideToggle("fast", function(){
					$__trigger_strOpen = '<img src="images/icons_sprites.gif" alt="extras" class="icon_plus"/> More extras';
					$__trigger_strClose = '<img src="images/icons_sprites.gif" alt="extras" class="icon_Minus"/> Close';
					($__trigger.text() == $__trigger_strOpen) ? $__trigger.html($__trigger_strClose) : $__trigger.html($__trigger_strOpen);
					//toggleSideExtras();
				});
				return false;
			});
			//function toggleSideExtras(){
				 //var $__sideExtras = $(('.prices .sideExtras'),$__root);
				//($__content.is(':visible')) ? $__sideExtras.show() : $__sideExtras.hide();
			//}
			//toggleSideExtras();
		});	
	},
	lightBox : function(){
		$.getScript("javascript/jqModal.js", function(){
			//set vars
			var $__modalWindow = '#modalWindow';
			var $__modalTrigger = 'a[rel="zoom"]';
			var $__modalHTML = '';
			$__modalHTML +=		'<div class="top">';
			$__modalHTML +=			'<a href="javascript:void()" id="closeModal"><span class="btntxt">Close</span><span class="icon_close"></span></a>';
			$__modalHTML +=		'</div>';
			$__modalHTML +=		'<div class="content">';
			$__modalHTML +=			'<div class="inner-top">';
			$__modalHTML +=				'<div class="inner-bottom">';
			$__modalHTML +=				'<div class="padding clear" id="jqmContent"></div>';
			$__modalHTML +=				'</div>';
			$__modalHTML +=			'</div>';
			$__modalHTML +=		'</div>';
			$__modalHTML +=		'<div class="bottom"></div>';
			$($__modalWindow).html($__modalHTML);
			var $__modalContent = $('#jqmContent', $__modalWindow);
			//load content 
			var loadModalContent = function(hash){
				var $__href = $(hash.t).attr('href');
				$($__modalContent).load($__href);
				hash.w.animate({opacity: "toggle"}, "fast");
			}
			//unloadmodal
			var closeModal = function(hash){
				hash.w.animate({opacity: "toggle"}, "fast", function(){
					hash.o.remove();
					$($__modalContent).empty();
				});
			}; 
			// initialise jqModal
			$($__modalWindow).jqm({
				modal : false,
				toTop :true,
				overlay: 60,
				trigger: $__modalTrigger,
				onHide : closeModal,
				onShow : loadModalContent
			});
			//bind close action to close button
			$('#closeModal', $__modalWindow).unbind('click').bind('click', function(e){
				e.preventDefault();
				$($__modalWindow).jqmHide(); 
			});
		});
	},
	addExtras: function() {
		var __arr, __j, __that = this, __side = {};
		
		var cleanValue = function(o){
			var __val, __pos, __cur = undefined;
			
			if (o.firstChild) {
				if (o.firstChild.nodeType == 3) {
					__val = o.firstChild.nodeValue; // get the first child out, which should be the cost as a String which will include a currency symbol
				} else {
					return null;
				}
			} else {
				__val = o;
			}
			
			__val = __val.replace(/^\s/, '');
			if ((__pos = __val.search(__that.vars.currencies)) != -1) {
				__cur = __val.charAt(__pos);
				__val = __val.replace(__that.vars.currencies, '');
			}
			
			return {cur: __cur, val: Number(__val) };
		};
		
		var amendTotal = function (o) {
			o.sml = __that.clearChildren(o.sml);
			o.lrg = __that.clearChildren(o.lrg);
			
			o.smlInput.value = o.smlVal;
			o.lrgInput.value = o.lrgVal;
			
			o.smlVal = __that.toDecimalString(o.smlVal);
			o.lrgVal = __that.toDecimalString(o.lrgVal);
			
			o.sml.appendChild(document.createTextNode(o.smlCur + o.smlVal));
			o.lrg.appendChild(document.createTextNode(o.lrgCur + o.lrgVal));
		}
		
		var addToSide = function (o) {
			var __cls = $('input', o)[0].attributes['name'].value;
			$("." + __cls + "Side").show('fast');
		}
		
		var removeFromSide = function (o) {
			var __cls = $('input', o)[0].attributes['name'].value;
			$("." + __cls + "Side").hide('fast');
			$("." + __cls + "Side").remove();
			
			var __rowLength = $(o).parents(".panel").find(".sideExtrasInner div");
			if(__rowLength.length==0){
				$(o).parents(".panel").find(".sideExtras").addClass("hide");
			}

		}
		
		var onClickHandler = function(e){
			
			var __t = FC.commonEventObject(e),
				__this = e.data.panel;
			
			if (__t.className == 'addable' || __t.className == 'added') {
			
				var __smlTotalNode = $(__t).parents(".panel").find(".small .total")[0];
				var __smlInputNode = $(__t).parents(".panel").find(".small").parent().siblings("input")[0];
				var __lrgTotalNode = $(__t).parents(".panel").find(".large .total")[0];
				var __lrgInputNode = $(__t).parents(".panel").find(".large").parent().siblings("input")[0];
				
			
				/*var __smlTotalNode = $('.small .total', __this)[0],
					__smlInputNode = $('.small', __this).siblings('input')[0],
					__lrgTotalNode = $('.large .total', __this)[0],
					__lrgInputNode = $('.large', __this).siblings('input')[0];
*/
				
				var __idxNum = Number(e.data.idx);
				//Build extras
				if(e.data.idx>=0){
					var __desc = e.data.h3;
					var __idx = e.data.idx;
					//Build div
					buildExtras(__t.id,__desc,__idx);
				}
				
				if (__smlTotalNode && __lrgTotalNode) {

					
					var __smlTotalVals = cleanValue(__smlTotalNode), __lrgTotalVals = cleanValue(__lrgTotalNode);
					
					if (__smlTotalVals && __lrgTotalNode) {
						var __tgtValue = Number(0);
						var __row = $(__t).parents('tr')[0];
						
						if (__t.className == 'addable') {
							__t.className = 'added';
							__tgtValue = Number(cleanValue(__t.value).val);
							__row.className = 'selected';
							addToSide(__row);
						} else  if (__t.className == 'added') {
							
							__t.className = 'addable';
							__tgtValue = -Number(cleanValue(__t.value).val);
							__row.className = '';
							removeFromSide(__row);
						}
						amendTotal({
							sml : __smlTotalNode,
							smlInput : __smlInputNode,
							smlCur : __smlTotalVals.cur,
							smlVal : Math.round(Number(__smlTotalVals.val += __tgtValue) * 100) / 100,
							lrg : __lrgTotalNode,
							lrgInput : __lrgInputNode,
							lrgCur : __lrgTotalVals.cur,
							lrgVal : Math.round(Number(__lrgTotalVals.val += __tgtValue) * 100) / 100
						});
						
						
					}
				}
				
				
			}
		};

		FC.isLteIE7 = (function () {
			/*@cc_on @*/ 
				/*@if (@_jscript_version <= 5.7) 
					return true;  
				@else @*/ 
					return false; 
			/*@end @*/
		})();
		
		var populateFromSelects = function (o, p) {
			// if there are any selects within this panel then change the value of the associated checkboxes
//			__price = $('.price', __rows[__j])[0];

			//Make sure all select boxes are set to the default values
			var __selects = $("td.quantity select");
			for(i=0;i<__selects.length;i++){
				__selects[i].selectedIndex=0;
			}
			
		};
		
		var populateFromCheckboxes = function (row, o, idx) {
			var __value = $('.addable', row)[0], __price;
			var __smlVal = cleanValue(o.sml), __lrgVal = cleanValue(o.lrg);
			
			if (__value.checked) {
				// if there are any selected checkboxes, set their className to 'added' and then update the sml and lge nodes.
				__value.className = 'added';
				__price = Number(cleanValue(__value.value).val);
				
				amendTotal({
					sml : o.sml,
					smlInput : o.smlInput,
					smlCur : __smlVal.cur,
					smlVal : Math.round(Number(__smlVal.val += __price) * 100) / 100,
					lrg : o.lrg,
					lrgInput : o.lrgInput,
					lrgCur : __lrgVal.cur,
					lrgVal : Math.round(Number(__lrgVal.val += __price) * 100) / 100
				});
				
				// go up to the parent and set the class on the TR and the display on the OnSide
				row.className = 'selected';
				
				var __desc = $("span.title", row).text();
				var __id = $("input", row)[0].id;
				//Build div
				buildExtras(__id,__desc,idx);
	
				addToSide(row);
			}
		};
		
		var onFirstRun = function(){
			var __j = Number(0), __rows, __k = Number(0), __nodes, __panel; 
			
			if (__arr = $('.panel')) {
				__j = __arr.length;
				

				
				while (__j--) {
					__panel = __arr[__j];

					//$(__panel).bind('click', onClickHandler);	
					
					// cycle through selects and checkboxes and add their values to the totals
					__nodes = {
						sml : $('.small .total', __panel)[0],
						smlInput : $('.small').parent().siblings('input')[0],
						lrg : $('.large .total', __panel)[0],
						lrgInput :  $('.large').parent().siblings('input')[0],
						par : __panel
					};
					__rows = $('tr', __panel);
					__k = __rows.length;
					
					while (__k--){
						populateFromSelects(__rows[__k], __nodes);
						populateFromCheckboxes(__rows[__k], __nodes, __k);
					}
					
					
					
					// tick boxes
					$("td.end input", __panel).each(function(i){
						var cost = $(this).val();
						var h3 = $(this).parents("tr").find("span.title").text();						
						$(this).bind('click', {idx:i, panel:__panel, cost:cost, h3:h3}, onClickHandler);							
					});		
					
					// select boxes
					$("td select", __panel).each(function(i){
						//var cost = $(this).val();
						//var h3 = $(this).parents("tr").find("span.title").text();						
						$(this).bind('change', function(){
							
							var __h3 = $(this).parents("tr").find("span.title").text();
							var __multiplier = $(this).val();
							var __input =  $(this).parents("tr").find("input")[0];
							var __val = $(this).parents("tr").find("span.price").text();
							
							var __allInputs = $(this).parents("table").find("input");
							var __relatedInput = $(this).parents("tr").find("input")[0];
							for(i=0;i<__allInputs.length;i++){
								if(__allInputs[i].id==__relatedInput.id){
									__idx=i;
								}
							}
							
							if(__input.checked){
								onClickHandler({target : __input, data:{panel:__panel, idx:__idx}});
								__input.value = Number(__val)*__multiplier;
								onClickHandler({target : __input, data:{panel:__panel, idx:__idx, h3:__h3}});
							} else {
								__input.value = Number(__val)*__multiplier;
							}
							
							
						});							
					});	
				}
				
				

				
			}
		};
		
		var buildExtras = function(id,desc,idx){

			var targ = $("#"+id).parents("div.panel").find(".sideExtras");
			
			var div = document.createElement("div");
			div.className=id+"Side";
			div.idx = idx;
			div.appendChild(document.createTextNode(desc));
			
			targ.removeClass("hide");
					
			
			var currentDivs = $(".sideExtrasInner div");

            var insertionPoint = 0
            
            for (var i = Number(0); i < currentDivs.length; i++) {
                        if (idx >= currentDivs[i].idx) {
                                    insertionPoint = i + 1;
                        } else {
                                    insertionPoint = i;
                                    break
                        }
            }
			
			if(insertionPoint==0){
				targ.find("h3").after(div);	
			}
			else{
				__temp = insertionPoint-1;
				$(currentDivs[__temp]).after(div);	
			}
			
			
			
		}
		
		onFirstRun();
		
		populateFromSelects = null;
		delete populateFromSelects;
		
		populateFromCheckboxes = null;
		delete populateFromCheckboxes;
		
		onFirstRun = null;
		delete onFirstRun;
	}
}
$(function () { 
	if($(".calendar").length){FC.calendar();}
	if($(".tooltip").length){FC.tooltip();}
	if ($('.panel').length) {FC.addExtras()};
	if($(".extras").length){FC.toggleextras();}
	if($("a[rel='zoom']").length){FC.lightBox();}
}); 

