

/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Color functions from Steve's Cross Browser Gradient Backgrounds v1.0 (steve@slayeroffice.com && http://slayeroffice.com/code/gradient/)
 *
 * $LastChangedDate: 2007-06-26 19:52:18 -0500 (Tue, 26 Jun 2007) $
 * $Rev: 2163 $
 *
 * Version 1.0
 */
(function($) {

/**
 * Adds a gradient to the background of an element.
 *
 * @example $('div').gradient({ from: '000000', to: 'CCCCCC' });
 *
 * @param Map options Settings/options to configure the gradient.
 * @option String from The hex color code to start the gradient with.
 * 		By default the value is "000000".
 * @option String to The hex color code to end the gradient with.
 * 		By default the value is "FFFFFF".
 * @option String direction This tells the gradient to be horizontal
 *      or vertical. By default the value is "horizontal".
 * @option Number length This is used to constrain the gradient to a
 *      particular width or height (depending on the direction). By default
 *      the length is set to null, which will use the width or height
 *      (depending on the direction) of the element.
 * @option String position This tells the gradient to be positioned
 *      at the top, bottom, left and/or right within the element. The
 *      value is just a string that specifices top or bottom and left or right.
 *      By default the value is 'top left'.
 *
 * @name gradient
 * @type jQuery
 * @cat Plugins/gradient
 * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 */
$.fn.gradient = function(options) {
	options = $.extend({ from: '000000', to: 'ffffff', direction: 'horizontal', position: 'top', length: null }, options || {});
	var createColorPath = function(startColor, endColor, distance) {
		var colorPath = [],
		    colorPercent = 1.0,
			distance = (distance < 100) ? distance : 100;
		do {
			colorPath[colorPath.length] = setColorHue(longHexToDec(startColor), colorPercent, longHexToDec(endColor));	
			colorPercent -= ((100/distance)*0.01);
		} while (colorPercent>0);
		return colorPath;
	},
	setColorHue = function(originColor, opacityPercent, maskRGB) {
		var returnColor = [];
		for (var i=0; i<originColor.length; i++)
			returnColor[i] = Math.round(originColor[i]*opacityPercent) + Math.round(maskRGB[i]*(1.0-opacityPercent));
		return returnColor;
	},
	longHexToDec = function(longHex) {
		return new Array(toDec(longHex.substring(0,2)),toDec(longHex.substring(2,4)),toDec(longHex.substring(4,6)));
	},
	toDec = function(hex) {
		return parseInt(hex,16);
	};
	return this.each(function() {
		var $this = $(this), width = $this.innerWidth(), height = $this.innerHeight(), x = 0, y = 0, w = 1, h = 1, html = [],
		    length = options.length || (options.direction == 'vertical' ? width : height),
		    position = (options.position == 'bottom' ? 'bottom:0;' : 'top:0;') + (options.position == 'right' ? 'right:0;' : 'left:0;'), 
		    colorArray = createColorPath(options.from, options.to, length);
		
		if (options.direction == 'horizontal') {
			h = Math.round(length/colorArray.length) || 1;
			w = width;
		} else {
			w = Math.round(length/colorArray.length) || 1;
			h = height;
		}
		
		html.push('<div class="gradient" style="position: absolute; ' + position + ' width: ' + (options.direction == 'vertical' ? length+"px" : "100%") +'; height: ' + (options.direction == 'vertical' ? "100%" : length+"px") + '; overflow: hidden; z-index: 0; background-color: #' + (options.position.indexOf('bottom') != -1 ? options.from : options.to) + '">');
		for(var i=0; i<colorArray.length; i++) {
			html.push('<div style="position:absolute;z-index:1;top:' + y + 'px;left:' + x + 'px;height:' + (options.direction == 'vertical' ? "100%" : h+"px") + ';width:' + (options.direction == 'vertical' ? w+"px" : "100%") + ';background-color:rgb(' + colorArray[i][0] + ',' + colorArray[i][1] + ',' + colorArray[i][2] + ');"></div>');
			options.direction == 'vertical' ? x+=w : y+=h;
			
			if ( y >= height || x >= width) break;
		}
		html.push('</div>');
		
		if ( $this.css('position') == 'static' )
			$this.css('position', 'relative');
		
		$this
			.html('<div style="display:' + $this.css("display") + '; position: relative; z-index: 2;">' + this.innerHTML + '</div>')
			.prepend(html.join(''));
	});
};

})(jQuery);

/*
	Masked Input plugin for jQuery
	Copyright (c) 2007-2009 Josh Bush (digitalbush.com)
	Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license) 
	Version: 1.2.2 (03/09/2009 22:39:06)
*/
(function($) {
var pasteEventName = ($.browser.msie ? 'paste' : 'input') + ".mask";
var iPhone = (window.orientation != undefined);
$.mask = {
	//Predefined character definitions
	definitions: {
		'9': "[0-9]",
		'a': "[A-Za-z]",
		'*': "[A-Za-z0-9]"
	}
};
$.fn.extend({
//Helper Function for Caret positioning
caret: function(begin, end) {
	if (this.length == 0) return;
	if (typeof begin == 'number') {
		end = (typeof end == 'number') ? end : begin;
		return this.each(function() {
			if (this.setSelectionRange) {
				this.focus();
				this.setSelectionRange(begin, end);
			} else if (this.createTextRange) {
				var range = this.createTextRange();
				range.collapse(true);
				range.moveEnd('character', end);
				range.moveStart('character', begin);
				range.select();
			}
		});
	} else {
		if (this[0].setSelectionRange) {
			begin = this[0].selectionStart;
			end = this[0].selectionEnd;
		} else if (document.selection && document.selection.createRange) {
			var range = document.selection.createRange();
			begin = 0 - range.duplicate().moveStart('character', -100000);
			end = begin + range.text.length;
		}
		return { begin: begin, end: end };
	}
},
unmask: function() { return this.trigger("unmask"); },
mask: function(mask, settings) {
	if (!mask && this.length > 0) {
		var input = $(this[0]);
		var tests = input.data("tests");
		return $.map(input.data("buffer"), function(c, i) {
			return tests[i] ? c : null;
		}).join('');
	}
	settings = $.extend({
		placeholder: "_",
		completed: null
	}, settings);
	var defs = $.mask.definitions;
	var tests = [];
	var partialPosition = mask.length;
	var firstNonMaskPos = null;
	var len = mask.length;

	$.each(mask.split(""), function(i, c) {
		if (c == '?') {
			len--;
			partialPosition = i;
		} else if (defs[c]) {
			tests.push(new RegExp(defs[c]));
			if(firstNonMaskPos==null)
				firstNonMaskPos =  tests.length - 1;
		} else {
			tests.push(null);
		}
	});
	return this.each(function() {
		var input = $(this);
		var buffer = $.map(mask.split(""), function(c, i) { if (c != '?') return defs[c] ? settings.placeholder : c });
		var ignore = false;  			//Variable for ignoring control keys
		var focusText = input.val();
		input.data("buffer", buffer).data("tests", tests);
		function seekNext(pos) {
			while (++pos <= len && !tests[pos]);
			return pos;
		};
		function shiftL(pos) {
			while (!tests[pos] && --pos >= 0);
			for (var i = pos; i < len; i++) {
				if (tests[i]) {
					buffer[i] = settings.placeholder;
					var j = seekNext(i);
					if (j < len && tests[i].test(buffer[j])) {
						buffer[i] = buffer[j];
					} else
						break;
				}
			}
			writeBuffer();
			input.caret(Math.max(firstNonMaskPos, pos));
		};
		function shiftR(pos) {
			for (var i = pos, c = settings.placeholder; i < len; i++) {
				if (tests[i]) {
					var j = seekNext(i);
					var t = buffer[i];
					buffer[i] = c;
					if (j < len && tests[j].test(t))
						c = t;
					else
						break;
				}
			}
		};
		function keydownEvent(e) {
			var pos = $(this).caret();
			var k = e.keyCode;
			ignore = (k < 16 || (k > 16 && k < 32) || (k > 32 && k < 41));

			//delete selection before proceeding
			if ((pos.begin - pos.end) != 0 && (!ignore || k == 8 || k == 46))
				clearBuffer(pos.begin, pos.end);
			//backspace, delete, and escape get special treatment
			if (k == 8 || k == 46 || (iPhone && k == 127)) {//backspace/delete
				shiftL(pos.begin + (k == 46 ? 0 : -1));
				return false;
			} else if (k == 27) {//escape
				input.val(focusText);
				input.caret(0, checkVal());
				return false;
			}
		};
		function keypressEvent(e) {
			if (ignore) {
				ignore = false;
				//Fixes Mac FF bug on backspace
				return (e.keyCode == 8) ? false : null;
			}
			e = e || window.event;
			var k = e.charCode || e.keyCode || e.which;
			var pos = $(this).caret();
			if (e.ctrlKey || e.altKey || e.metaKey) {//Ignore
				return true;
			} else if ((k >= 32 && k <= 125) || k > 186) {//typeable characters
				var p = seekNext(pos.begin - 1);
				if (p < len) {
					var c = String.fromCharCode(k);
					if (tests[p].test(c)) {
						shiftR(p);
						buffer[p] = c;
						writeBuffer();
						var next = seekNext(p);
						$(this).caret(next);
						if (settings.completed && next == len)
							settings.completed.call(input);
					}
				}
			}
			return false;
		};
		function clearBuffer(start, end) {
			for (var i = start; i < end && i < len; i++) {
				if (tests[i])
					buffer[i] = settings.placeholder;
			}
		};
		function writeBuffer() { return input.val(buffer.join('')).val(); };
		function checkVal(allow) {
			//try to place characters where they belong
			var test = input.val();
			var lastMatch = -1;
			for (var i = 0, pos = 0; i < len; i++) {
				if (tests[i]) {
					buffer[i] = settings.placeholder;
					while (pos++ < test.length) {
						var c = test.charAt(pos - 1);
						if (tests[i].test(c)) {
							buffer[i] = c;
							lastMatch = i;
							break;
						}
					}
					if (pos > test.length)
						break;
				} else if (buffer[i] == test[pos] && i!=partialPosition) {
					pos++;
					lastMatch = i;
				} 
			}
			if (!allow && lastMatch + 1 < partialPosition) {
				input.val("");
				clearBuffer(0, len);
			} else if (allow || lastMatch + 1 >= partialPosition) {
				writeBuffer();
				if (!allow) input.val(input.val().substring(0, lastMatch + 1));
			}
			return (partialPosition ? i : firstNonMaskPos);
		};
		if (!input.attr("readonly"))
			input
			.one("unmask", function() {
				input
					.unbind(".mask")
					.removeData("buffer")
					.removeData("tests");
			})
			.bind("focus.mask", function() {
				focusText = input.val();
				var pos = checkVal();
				writeBuffer();
				setTimeout(function() {
					if (pos == mask.length)
						input.caret(0, pos);
					else
						input.caret(pos);
				}, 0);
			})
			.bind("blur.mask", function() {
				checkVal();
				if (input.val() != focusText)
					input.change();
			})
			.bind("keydown.mask", keydownEvent)
			.bind("keypress.mask", keypressEvent)
			.bind(pasteEventName, function() {
				setTimeout(function() { input.caret(checkVal(true)); }, 0);
			});
		//checkVal(); //Perform initial check for existing values
	});
}
});
})(jQuery);

//for hotel
function lookup_hotel(suggest_id,type,inputString,set_name,set_id,site_id) {
	if(inputString.length == 0) {
		// Hide the suggestion box.
		$('#suggestions'+suggest_id).hide();
	} else {
		$.post("/admin/autoSuggest.php?suggest_id="+suggest_id+"&set_name="+set_name+"&set_id="+set_id+"&type="+type+"&site_id="+site_id, {q: ""+inputString+""}, function(data){
			if(data.length >0) {
				$('#suggestions'+suggest_id).show();
				$('#autoSuggestionsList'+suggest_id).html(data);
			}
		});
	}
} // lookup hotel

//set_name: id of input type in which you want to set choosen value
//set_nameval : choosen value
//set_id : id of hidden input type in which you want to set choosen value's id
//set_idval  : choosen value's id
function fill(suggest_id,set_name,set_nameval,set_id,set_idval) {
	$('#'+set_name).val(set_nameval);
	$('#'+set_id).val(set_idval);
	setTimeout("$('#suggestions"+suggest_id+"').hide();", 200);
	if($.browser.msie && $.browser.version <7 && set_id=='fromAirportCode'){
				    $('#inmonth').css('visibility','visible');
				    $('#inday').css('visibility','visible');
				    $('#inyear').css('visibility','visible');
				    $('#outmonth').css('visibility','visible');
				    $('#outday').css('visibility','visible');
				    $('#outyear').css('visibility','visible');
				}
}

//set_name: id of input type in which you want to set choosen value
//set_nameval : choosen value
//set_id : id of hidden input type in which you want to set choosen value's id
//set_idval  : choosen value's id
function fill_flag(suggest_id,set_name,set_nameval,set_id,set_idval, flag_val) {
    $('#'+set_name).val(set_nameval);
    $('#'+set_id).val(set_idval);
    $('#show_if_live').hide();
    $('#show_if_not_live').hide();
    if(flag_val == 1)
    {
        $('#show_if_live').show();
    }else
    {
        $('#show_if_not_live').show();
    }
    setTimeout("$('#suggestions"+suggest_id+"').hide();", 200);
}

//for site,city
function lookup(suggest_id,type,inputString,set_name,set_id) {
	if(inputString.length == 0 || inputString.length < 3) {
		// Hide the suggestion box.
		$('#suggestions'+suggest_id).hide();
		if($.browser.msie && $.browser.version <7 && set_id=='fromAirportCode'){
				    $('#inmonth').css('visibility','visible');
				    $('#inday').css('visibility','visible');
				    $('#inyear').css('visibility','visible');
				    $('#outmonth').css('visibility','visible');
				    $('#outday').css('visibility','visible');
				    $('#outyear').css('visibility','visible');
				}
	} else {
		$.post("/includes/autoSuggest.php?suggest_id="+suggest_id+"&set_name="+set_name+"&set_id="+set_id+"&type="+type, {q: ""+inputString+""}, function(data){
			if(data.length >0) {
				$('#suggestions'+suggest_id).show();
				$('#autoSuggestionsList'+suggest_id).html(data);
				if($.browser.msie && $.browser.version <7 && set_id=='fromAirportCode' && data.length>2){
				    $('#inmonth').css('visibility','hidden');
				    $('#inday').css('visibility','hidden');
				    $('#inyear').css('visibility','hidden');
				    $('#outmonth').css('visibility','hidden');
				    $('#outday').css('visibility','hidden');
				    $('#outyear').css('visibility','hidden');
				}
			}
		});
	}
} // lookup

//for site,city
function lookup1(suggest_id,type,inputString,set_name,set_id,id) {
	if(inputString.length == 0 || inputString.length < 3) {
		// Hide the suggestion box.
		$('#suggestions'+suggest_id).hide();
		if($.browser.msie && $.browser.version <7 && set_id=='fromAirportCode'){
				    $('#inmonth').css('visibility','visible');
				    $('#inday').css('visibility','visible');
				    $('#inyear').css('visibility','visible');
				    $('#outmonth').css('visibility','visible');
				    $('#outday').css('visibility','visible');
				    $('#outyear').css('visibility','visible');
				}
	} else {
		$.post("/includes/autoSuggest.php?id="+id+"&suggest_id="+suggest_id+"&set_name="+set_name+"&set_id="+set_id+"&type="+type, {q: ""+inputString+""}, function(data){
			if(data.length >0) {
				$('#suggestions'+suggest_id).show();
				$('#autoSuggestionsList'+suggest_id).html(data);
				if($.browser.msie && $.browser.version <7 && set_id=='fromAirportCode' && data.length>2){
				    $('#inmonth').css('visibility','hidden');
				    $('#inday').css('visibility','hidden');
				    $('#inyear').css('visibility','hidden');
				    $('#outmonth').css('visibility','hidden');
				    $('#outday').css('visibility','hidden');
				    $('#outyear').css('visibility','hidden');
				}
			}
		});
	}
} // lookup





/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-12-20 08:46:55 -0600 (Thu, 20 Dec 2007) $
 * $Rev: 4259 $
 *
 * Version: 1.2
 *
 * Requires: jQuery 1.2+
 */

(function($){
	
$.dimensions = {
	version: '1.2'
};

// Create innerHeight, innerWidth, outerHeight and outerWidth methods
$.each( [ 'Height', 'Width' ], function(i, name){
	
	// innerHeight and innerWidth
	$.fn[ 'inner' + name ] = function() {
		if (!this[0]) return;
		
		var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
		    borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
		
		return this.is(':visible') ? this[0]['client' + name] : num( this, name.toLowerCase() ) + num(this, 'padding' + torl) + num(this, 'padding' + borr);
	};
	
	// outerHeight and outerWidth
	$.fn[ 'outer' + name ] = function(options) {
		if (!this[0]) return;
		
		var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
		    borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
		
		options = $.extend({ margin: false }, options || {});
		
		var val = this.is(':visible') ? 
				this[0]['offset' + name] : 
				num( this, name.toLowerCase() )
					+ num(this, 'border' + torl + 'Width') + num(this, 'border' + borr + 'Width')
					+ num(this, 'padding' + torl) + num(this, 'padding' + borr);
		
		return val + (options.margin ? (num(this, 'margin' + torl) + num(this, 'margin' + borr)) : 0);
	};
});

// Create scrollLeft and scrollTop methods
$.each( ['Left', 'Top'], function(i, name) {
	$.fn[ 'scroll' + name ] = function(val) {
		if (!this[0]) return;
		
		return val != undefined ?
		
			// Set the scroll offset
			this.each(function() {
				this == window || this == document ?
					window.scrollTo( 
						name == 'Left' ? val : $(window)[ 'scrollLeft' ](),
						name == 'Top'  ? val : $(window)[ 'scrollTop'  ]()
					) :
					this[ 'scroll' + name ] = val;
			}) :
			
			// Return the scroll offset
			this[0] == window || this[0] == document ?
				self[ (name == 'Left' ? 'pageXOffset' : 'pageYOffset') ] ||
					$.boxModel && document.documentElement[ 'scroll' + name ] ||
					document.body[ 'scroll' + name ] :
				this[0][ 'scroll' + name ];
	};
});

$.fn.extend({
	position: function() {
		var left = 0, top = 0, elem = this[0], offset, parentOffset, offsetParent, results;
		
		if (elem) {
			// Get *real* offsetParent
			offsetParent = this.offsetParent();
			
			// Get correct offsets
			offset       = this.offset();
			parentOffset = offsetParent.offset();
			
			// Subtract element margins
			offset.top  -= num(elem, 'marginTop');
			offset.left -= num(elem, 'marginLeft');
			
			// Add offsetParent borders
			parentOffset.top  += num(offsetParent, 'borderTopWidth');
			parentOffset.left += num(offsetParent, 'borderLeftWidth');
			
			// Subtract the two offsets
			results = {
				top:  offset.top  - parentOffset.top,
				left: offset.left - parentOffset.left
			};
		}
		
		return results;
	},
	
	offsetParent: function() {
		var offsetParent = this[0].offsetParent;
		while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && $.css(offsetParent, 'position') == 'static') )
			offsetParent = offsetParent.offsetParent;
		return $(offsetParent);
	}
});

function num(el, prop) {
	return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0;
};

})(jQuery);

function makeHttpRequestObj(){
var ajaxRequest;
try{ajaxRequest=new XMLHttpRequest();}catch(Error){
	try{ajaxRequest=new ActiveXObject('msxml.XMLHTTP');}catch(Error){
		try{ajaxRequest=new ActiveXObject('Microsoft.XMLHTTP');}catch(Error){
			ajaxRequest=null;
		}
	}
} return ajaxRequest;
}
function i4tracker(action){
var ajaxRequest=makeHttpRequestObj(); qString='/i4tracker.php?action='+action; ajaxRequest.open("GET",qString,true); ajaxRequest.send(qString);
}

function bookmark(sessionid){
 var url="http://www.i4vegas.com/index.php/page0.44.html";
 var title="i4vegas.com - Las Vegas Discounts"
 var mt = /mac/i;
 var mac = mt.test(navigator.platform);
 if (document.all){
  if (mac){
   alert("For Quick Access to the Best Las Vegas Hotel Rates:\nClick <OK>, then press Apple+D to bookmark i4vegas.com");
  }else{
   window.external.AddFavorite(url,title);  var tag="bookmark_IE"  }
 }else{
  if (mac) {
   alert("For Quick Access to the Best Las Vegas Hotel Rates:\nClick <OK>, then press Apple+D to bookmark i4vegas.com");
  } else {
   alert("For Quick Access to the Best Las Vegas Hotel Rates:\nClick <OK>, then press CTRL+D to bookmark i4vegas.com");
  }
  var tag="bookmark_other";
 }
 if (document.imgtracker.src) {  logChange(sessionid,tag); }
}
function focusSearch(){ if (document.search && document.search.Submit) { document.search.Submit.focus(); }}
/*function showWaitD(red) {
 setTimeout('showWait('+red+')', 500);
}*/
todayDate = new Date();
function setToday(secs) { todayDate = new Date(secs*1000);}
function doSO(f,tV,tF){
  for(i=0;i<f[tF].options.length;i++)
   if(f[tF].options[i].value==tV){ f[tF].options[i].selected=true; }
}
function dateChange(f,field){
 //window.status = field.name;
 thisdate = new Date(f.inyear[f.inyear.selectedIndex].value, f.inmonth[f.inmonth.selectedIndex].value-1,
                     f.inday[f.inday.selectedIndex].value);
 outdate  = new Date(f.outyear[f.outyear.selectedIndex].value, f.outmonth[f.outmonth.selectedIndex].value-1,
                     f.outday[f.outday.selectedIndex].value);
 anotherdate = new Date(thisdate);
 testdate = new Date(outdate - (86400000*14));
 if ((thisdate-0)<(outdate-0) && anotherdate >= testdate && ((f.inmonth[f.inmonth.selectedIndex].value-1) >= todayDate.getMonth() ||
     f.inyear[f.inyear.selectedIndex].value > todayDate.getFullYear())) {
  return;
 }
 msecs = (thisdate-0);
 twoday = new Date(msecs+(86400000*2));
 im = thisdate.getMonth()+1;
 id = thisdate.getDate();
 iy = thisdate.getFullYear();
 om = twoday.getMonth()+1;
 od = twoday.getDate();
 oy = twoday.getFullYear();
 if (im < (todayDate.getMonth()+1) && iy == todayDate.getFullYear()) {
  //window.status = im + " < " + (todayDate.getMonth()+1);
  /*
  newsecs = (todayDate-0);
  newtwoday = new Date(newsecs+(86400000*2));
  */
//  im = todayDate.getMonth()+1;
//  om = newtwoday.getMonth()+1;
  if (field.name != "inyear" && field.name != "outyear") {
   iy = thisdate.getFullYear() + 1;
   oy = outdate.getFullYear() + 1;
  }
 // id = todayDate.getDate();
 // od = newtwoday.getDate();
 }

 doSO(f,im,"inmonth");
 doSO(f,id,"inday");
 doSO(f,iy,"inyear");
 doSO(f,om,"outmonth");
 doSO(f,od,"outday");
 doSO(f,oy,"outyear");
}

function validateCity(f){
//  if(f.FrAirport.value == ""){
//    alert("Please enter the city you are departing from. There may be regional travel discounts.");
//    f.FrAirport.focus();
//    return false;
//  } else {
    return true;
//  }
}
var formSubmitted;
function checkSubmit(){
 if (formSubmitted) {
  alert('Already processing, please wait a moment...');
  return false;
 } else {
  formSubmitted = true;
  return true;
 }
}
function logChange(sessionid,tag,form){
 window.status='Done';
 if (form) {
  str="";
  for (x=0;x<form.elements.length;x++) {
   if (form.elements[x].value && form.elements[x].name!='CCnum') {
    str = str + "&" + form.elements[x].name + "=" + form.elements[x].value;
   }
  }
  eval("if(document.imgtracker) {document.imgtracker.src = '/imgtracker.php?sessionid=' + sessionid + '&tag=' + tag + '&data=' + escape(str) }");
 } else {
  eval("if(document.imgtracker) {document.imgtracker.src = '/imgtracker.php?sessionid=' + sessionid + '&tag=' + tag}");
 }
 window.status='Done';
}
var nameSet;
function setFirstRoomname(form){
 for (x=0;x<form.elements.length;x++) {
  if (form.elements[x].name.indexOf("roomname[]")!=-1) {
   if (!nameSet) {
    form.elements[x].value = form.fname.value + " " + form.lname.value;
    nameSet = true;
   }
   break;
  }
 }
}
var ccNameSet;
function setCCName(form){
 for (x=0;x<form.elements.length;x++) {
  if (form.elements[x].name.indexOf("CCname")!=-1) {
   if (!ccNameSet) {
    form.elements[x].value = form.fname.value + " " + form.lname.value;
    ccNameSet = true;
   }
   break;
  }
 }
}
function setFirstPassenger(form){
 for (x=0;x<form.elements.length;x++) {
  if (form.elements[x].name.indexOf("airfname[]")!=-1) {
   if (!nameSet) {
    form.elements[x].value = form.fname.value;
   }
   break;
  }
 }
 for (x=0;x<form.elements.length;x++) {
  if (form.elements[x].name.indexOf("airlname[]")!=-1) {
   if (!nameSet) {
    form.elements[x].value = form.lname.value;
   }
   break;
  }
 }
 nameSet = true;
}
function setFirstRoomname2(form){
 for (x=0;x<form.elements.length;x++) {
  if (form.elements[x].name.indexOf("roomfname[]")!=-1) {
   if (!nameSet) {
    form.elements[x].value = form.fname.value;
   }
   break;
  }
 }
 for (x=0;x<form.elements.length;x++){
  if (form.elements[x].name.indexOf("roomlname[]")!=-1) {
   if (!nameSet) {
    form.elements[x].value = form.lname.value;
   }
   break;
  }
 }
 nameSet = true;
}
function setBillingInfo(form){
  if (form.same.checked) {
   form.badd1.value  = form.add1.value;
   form.badd2.value  = form.add2.value;
   form.bzip.value   = form.zip.value;
   form.bcity.value  = form.city.value;
   form.bstate.value = form.state.value;
  }
}
// same as above function but called from submit button of lightbox form
function checkDatesSubmit(obj){
  if(obj.form) {
	  inday1    = Number(obj.form.inday[obj.form.inday.selectedIndex].value);
	  inmonth1  = Number(obj.form.inmonth[obj.form.inmonth.selectedIndex].value);
	  inyear1   = Number(obj.form.inyear[obj.form.inyear.selectedIndex].value);

	  outday1   = Number(obj.form.outday[obj.form.outday.selectedIndex].value);
	  outmonth1 = Number(obj.form.outmonth[obj.form.outmonth.selectedIndex].value);
	  outyear1  = Number(obj.form.outyear[obj.form.outyear.selectedIndex].value);
  } else {
	  inday1    = Number(inday.value);
	  inmonth1  = Number(inmonth.value);
	  inyear1   = Number(inyear.value);

	  outday1   = Number(outday.value);
	  outmonth1 = Number(outmonth.value);
	  outyear1  = Number(outyear.value);
  }
  d1 = new Date(inyear1,inmonth1-1,inday1);
  d2 = new Date(inyear1,inmonth1-1,1);
  d3 = new Date(outyear1,outmonth1-1,outday1);
  d4 = todayDate;
  d5 = new Date(d4.getFullYear(),d4.getMonth(),d4.getDate());
  message = ""
  var diff= d3.getTime()-d1.getTime();
  diff=diff/86400000;
  var chkin = inmonth1 +"-"+inday1+"-"+inyear1;
  var chkout = outmonth1 +"-"+outday1+"-"+outyear1;
 // window.status = outyear + "-" + outmonth + "-" + outday + " = " + d3;
  if (d1.getMonth() != d2.getMonth()) { message += "* Your check-in date is not valid.\n"; }
  if (d1.getTime() >= d3.getTime()) { message += "* Your check-out date must not be the same, or before your check-in date.\n"; }
  if (d1.getTime() < (d5.getTime()-86400000)) { message += "* Your check-in date may not be before today.\n"; }
  if(diff>90){ message += "* Search period cannot be longer than 90 days. "+ chkin + " thru " + chkout + " ("+diff+" days). Please modify your check-in or check-out date to reduce the search period to 90 days or less.\n"; }
  if (message.length > 0) { alert("Please address the following errors:\n" + message);
   return false;
  }
  return true;
}
function validateForm(form) {
  message = ""
  // Check Name
  if (isEmpty(form.fname.value)) { message += "* Please enter your first name\n"; }
  if (isEmpty(form.lname.value)) { message += "* Please enter your last name\n"; }
  // Check Address
  if (isEmpty(form.add1.value)) { message += "* Please enter your street address\n"; }
  // Check City/State/Zip
  if (isEmpty(form.city.value)) { message += "* Please enter your city\n"; }
  if (!isStateCode(form.state.value.toUpperCase())) {   message += "* Please enter a valid U.S. state abbreviation (CA for California,etc)\n"; }
  if (!isZipCode(form.zip.value)) { message += "* Please enter a valid 5 digit U.S. zip code\n"; }
  // Check Phone
  if (!isPhone(form.phone.value)) { message += "* Please enter a valid 10 digit U.S. phone number\n"; } 
  else {   form.phone.value = formatPhone(form.phone.value); }
  // Check E-mail
  if (!isEmail(form.email.value)) { message += "* Please enter a valid e-mail address\n"; }
  if (isEmpty(form.CCnum.value)) { message += "* Please enter your credit card number\n"; } 
  else {
   // Check Credit Card Type
   if (!checkCardType(form)) { message += "* Please make sure you have selected the correct credit card type\n"; }
   // Check Credit Card Luhn Mod 10
   if (!isCreditCard(form.CCnum.value)) { message += "* Please make sure you have entered the credit card number correctly\n"; }
  }
  // Check Credit Card Exp.
  if (!checkExp(form.CCexp.value)) { message += "* Please enter a valid credit card expiration date (MM/YYYY)\n"; }
  // Check Credit card Name
  if (isEmpty(form.CCname.value)) { message += "* Please enter the credit card holder's name (first last)\n"; }
  // Check Credit Card Address
  if (isEmpty(form.badd1.value) && !form.same.checked) { message += "* Please enter your billing address\n"; }
  // Check Credit Card City/State/Zip
  if (isEmpty(form.bcity.value) && !form.same.checked) { message += "* Please enter your billing city\n"; }
  if (!isStateCode(form.bstate.value) && !form.same.checked) { message += "* Please enter a valid U.S. state abbreviation for your billing address\n"; }
  if (!isZipCode(form.bzip.value) && !form.same.checked) { message += "* Please enter a valid 5 digit U.S. zip code for your billing address\n"; }
  // Check if we had an error.
  if (message.length > 0) {   alert("Please address the following errors:\n" + message); return false; } 
  else {   //form.submit();
   return true;
  }
}
function isEmail(st) {
 if ((st.indexOf("@") == -1) || (st.charAt(0) == ".") ||
     (st.charAt(0) == "@") || (st.length < 6) || (st.indexOf(".") == -1) ||
     (st.charAt(st.indexOf("@")+1) == ".") || (st.charAt(st.indexOf("@")-1) == "."))
  { return false; }
 return true;
}
var USStateCodeDelimiter = "|";
var USStateCodes = "AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|WY|AE|AA|AE|AE|AP";
function isStateCode(s){
return ( (USStateCodes.indexOf(s) != -1) && (s.indexOf(USStateCodeDelimiter) == -1) )
}
function isEmpty(s){  return ((s == null) || (s.length == 0))}
// Removes all characters which do NOT appear in string bag
// from string s.
function stripCharsNotInBag(s,bag){
    var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is in bag, append to returnString.
    for (i = 0; i < s.length; i++){
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1) returnString += c;
    }
    return returnString;
}
function isPhone(st){
 st =  stripCharsNotInBag (st,"0123456789");
 return (st.length == 10);
}
function formatPhone(st){
 st = stripCharsNotInBag (st,"0123456789");
 st = st.split("");
 return "(" + st[0] + st[1] + st[2] + ") " + st[3] + st[4] + st[5] + "-" + st[6] + st[7] + st[8] + st[9];
}
function isZipCode(st){
 st =  stripCharsNotInBag (st,"0123456789");
 return (st.length == 5);
}
function checkExp(st){
 st = st.split("/");
 if (st.length < 2){
  return false;
 } else if ((st[0] >= 1 && st[0] <= 12) && st[1].length == 4 && st[1] >= 2002) {
    return true;
 }
 return false;
}
function checkCardType(form){
  CCtype = form.CCtype[form.CCtype.selectedIndex].value;
  CCnum = stripCharsNotInBag (form.CCnum.value, "0123456789");
  if (CCtype == "Visa"){
    return isVisa(CCnum);
  } else if (CCtype == "Mastercard") {
    return isMasterCard(CCnum);
  } else if (CCtype == "Discover") {
    return isDiscover(CCnum);
  } else if (CCtype == "Amex") {
    return isAmericanExpress(CCnum);
  }
}
// Test card to see if it passes Luhn Mod-10
function isCreditCard(st){
  if (st=="7777999999999999") return true;
  st = stripCharsNotInBag (st, "0123456789");
  // Encoding only works on cards with less than 19 digits
  if (st.length > 19)
    return (false);
  sum = 0; mul = 1; l = st.length;
  for (i = 0; i < l; i++){
    digit = st.substring(l-i-1,l-i);
    tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)      mul++;
    else      mul--;
  }
  if ((sum % 10) == 0)    return (true);  
  else    return (false);

} // END FUNCTION isCreditCard()
function isVisa(cc){
  if (((cc.length == 16) || (cc.length == 13)) && (cc.substring(0,1) == 4))
    return isCreditCard(cc);
  return false;
}  // END FUNCTION isVisa()
function isMasterCard(cc){
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 16) && (firstdig == 5) && ((seconddig >= 1) && (seconddig <= 5)))
    return isCreditCard(cc);
  return false;
} // END FUNCTION isMasterCard()
function isAmericanExpress(cc){
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 15) && (firstdig == 3) && ((seconddig == 4) || (seconddig == 7)))
    return isCreditCard(cc);
  return false;
} // END FUNCTION isAmericanExpress()
function isDiscover(cc){
  first4digs = cc.substring(0,4);
  if ((cc.length == 16) && (first4digs == "6011"))
    return isCreditCard(cc);
  return false;
} // END FUNCTION isDiscover()
function readCookie(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 c.substring(nameEQ.length,c.length);
	}
	return null;
}
function dateChangeIn(val){
var cur= this;
var val1=val.split('/');
cur.form.inmonth.value=val1[0];
cur.form.inday.value=Number(val1[1]);
cur.form.inyear.value=Number(val1[2]);
checkValidDate(cur);
}
function dateChangeOut(val){
var cur= this;
var val1=val.split('/');
cur.form.outmonth.value=val1[0];
cur.form.outday.value=Number(val1[1]);
cur.form.outyear.value=Number(val1[2]);
checkValidDate(cur);
}
function checkValidDate(cur){
var indate  = new Date(cur.form.inyear.value,Number(cur.form.inmonth.value)-1,cur.form.inday.value);
var outdate  = new Date(cur.form.outyear.value,Number(cur.form.outmonth.value)-1,cur.form.outday.value);
diff= outdate.getTime()-indate.getTime();
diff=diff/86400000;
if(!(diff>0  && diff<30)){
    outdate = indate;
    outdate.setDate(indate.getDate()+2);
}
cur.form.outmonth.value=(outdate.getMonth()+1)<10?"0"+(outdate.getMonth()+1):(outdate.getMonth()+1);
cur.form.outday.value=outdate.getDate();
cur.form.outyear.value=outdate.getFullYear();
cur.form.datepicker2.value=cur.form.outmonth.value+'/'+cur.form.outday.value+'/'+cur.form.outyear.value
}
function checkDuplicatePassenegrName(form){
	var allnames=new Array();
	var k=0;
	for (var i=0;i<form.roomfname.length;i++) {
		if(mytrim(form.roomfname[i].value)==''){
			alert('Please type in the names of the persons checking in.');
			return false;
		}
		var user_input = mytrim(form.roomfname[i].value)+" "+mytrim(form.roomlname[i].value);
		user_input = user_input.toLowerCase();
		if(i==0){
			allnames[k++]=user_input;
		}else{
			var max=allnames.length;
			for (var j=0;j<max;j++){
				if(user_input==allnames[j]){
					//alert("Check-in Person number: "+(i+1)+" and Check-in Person number: "+(j+1)+" have same name or empty please provide a different names.");
					alert('Please provide different names for each room.')
					return false;
				}
				else{ allnames[k++]=user_input;	}
			}
		}
	}
	return true;
}
function mytrim(str){
var str= str.replace(/(^\s+)|(\s+$)/g,'');
return str.replace(/ {2,}/g,' ');
}
function validateReview(frm){
     message = ""
     // Check Name
     if (isEmpty(document.forms[frm].guest_name.value)){
         message += "* Please enter your name\n";
     }else if (isEmpty(document.forms[frm].guest_email.value)) {
         message += "* Please enter your email\n";
     }
     if(message.length>0)
     { alert(message); return false; }
}
// wait page variable set here - SEO related location change
function EmailSignUp(sessid,email_source){
    var email= $("#email_signup_form_email").val();
    if(!isEmail(email)){
     window.alert('Please enter a valid e-mail address.');logChange(sessid,'es_err_'+email_source);
     return;
    }
    var dataString ="email="+email+"&source="+$("#email_signup_form_source").val()+"&tag="+$("#email_signup_form_tag").val();
    $.ajax({
        type: "POST",
        url: '/Emailsignup/',
        data: dataString,
        success: function(html) {
            if(html.indexOf('YES')>=0){
                alert('Thank you! You are now registered to receive our special offers via e-mail.');
                $('#emailsignform_complete').css('display','block');
                $('#emailsignform').css('display','none');
            }else{
                alert('Problem with email sign up.Please try again with a valid email address.');
            }
        }
    });
}

/**
 * jQuery lightBox plugin
 * This jQuery plugin was inspired and based on Lightbox 2 by Lokesh Dhakar (http://www.huddletogether.com/projects/lightbox2/)
 * and adapted to me for use like a plugin from jQuery.
 * @name jquery-lightbox-0.5.js
 * @author Leandro Vieira Pinho - http://leandrovieira.com
 * @version 0.5
 * @date April 11, 2008
 * @category jQuery plugin
 * @copyright (c) 2008 Leandro Vieira Pinho (leandrovieira.com)
 * @license CC Attribution-No Derivative Works 2.5 Brazil - http://creativecommons.org/licenses/by-nd/2.5/br/deed.en_US
 * @example Visit http://leandrovieira.com/projects/jquery/lightbox/ for more informations about this jQuery plugin
 */

// Offering a Custom Alias suport - More info: http://docs.jquery.com/Plugins/Authoring#Custom_Alias
(function($) {
	/**
	 * $ is an alias to jQuery object
	 *
	 */
	$.fn.lightBox = function(settings) {
		// Settings to configure the jQuery lightBox plugin how you like
		settings = jQuery.extend({
			// Configuration related to overlay
			overlayBgColor: 		'#000',		// (string) Background color to overlay; inform a hexadecimal value like: #RRGGBB. Where RR, GG, and BB are the hexadecimal values for the red, green, and blue values of the color.
			overlayOpacity:			0.8,		// (integer) Opacity value to overlay; inform: 0.X. Where X are number from 0 to 9
			// Configuration related to navigation
			fixedNavigation:		false,		// (boolean) Boolean that informs if the navigation (next and prev button) will be fixed or not in the interface.
			// Configuration related to images
			imageLoading:			'/img/i4content/lightbox-ico-loading.gif',		// (string) Path and the name of the loading icon
			imageBtnPrev:			'/img/i4content/lightbox-btn-prev.gif',			// (string) Path and the name of the prev button image
			imageBtnNext:			'/img/i4content/lightbox-btn-next.gif',			// (string) Path and the name of the next button image
			imageBtnClose:			'/img/i4content/lightbox-btn-close.gif',		// (string) Path and the name of the close btn
			imageBlank:				'/img/i4content/lightbox-blank.gif',			// (string) Path and the name of a blank image (one pixel)
			// Configuration related to container image box
			containerBorderSize:	10,			// (integer) If you adjust the padding in the CSS for the container, #lightbox-container-image-box, you will need to update this value
			containerResizeSpeed:	400,		// (integer) Specify the resize duration of container image. These number are miliseconds. 400 is default.
			// Configuration related to texts in caption. For example: Image 2 of 8. You can alter either "Image" and "of" texts.
			txtImage:				'Image',	// (string) Specify text "Image"
			txtOf:					'of',		// (string) Specify text "of"
			// Configuration related to keyboard navigation
			keyToClose:				'c',		// (string) (c = close) Letter to close the jQuery lightBox interface. Beyond this letter, the letter X and the SCAPE key is used to.
			keyToPrev:				'p',		// (string) (p = previous) Letter to show the previous image
			keyToNext:				'n',		// (string) (n = next) Letter to show the next image.
			// Don´t alter these variables in any way
			imageArray:				[],
			activeImage:			0
		},settings);
		// Caching the jQuery object with all elements matched
		var jQueryMatchedObj = this; // This, in this context, refer to jQuery object
		/**
		 * Initializing the plugin calling the start function
		 *
		 * @return boolean false
		 */
		function _initialize() {
			_start(this,jQueryMatchedObj); // This, in this context, refer to object (link) which the user have clicked
			return false; // Avoid the browser following the link
		}
		/**
		 * Start the jQuery lightBox plugin
		 *
		 * @param object objClicked The object (link) whick the user have clicked
		 * @param object jQueryMatchedObj The jQuery object with all elements matched
		 */
		function _start(objClicked,jQueryMatchedObj) {
			// Hime some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
			//$('embed, object, select').css({ 'visibility' : 'hidden' });
			// use the form id to ensure only main form's element are hidden
			$("#search_form_main :input[name=inday]").css({ 'visibility' : 'hidden' });
			$("#search_form_main :input[name=inmonth]").css({ 'visibility' : 'hidden' });
			$("#search_form_main :input[name=inyear]").css({ 'visibility' : 'hidden' });
			$("#search_form_main :input[name=outday]").css({ 'visibility' : 'hidden' });
			$("#search_form_main :input[name=outmonth]").css({ 'visibility' : 'hidden' });
			$("#search_form_main :input[name=outyear]").css({ 'visibility' : 'hidden' });
			$("#search_form_main :input[name=search_area]").css({ 'visibility' : 'hidden' });
			$('#lm_type,#numrooms').css({ 'visibility' : 'hidden' });
			


			// Call the function to create the markup structure; style some elements; assign events in some elements.
			_set_interface();
			var chkin = $("#search_form_main :input[name=fullcheckin]").val()
			var val1 = chkin.split('/');
			inday    = Number(val1[1]);
			inmonth  = Number(val1[0]);
			inyear   = Number(val1[2])>2000?Number(val1[2]):2000+Number(val1[2]);
			inmonth=inmonth<10?"0"+inmonth:inmonth;
			$("#search_lightbox_form1 :input[name=inmonth]").val(inmonth);
			$("#search_lightbox_form1 :input[name=inday]").val(inday);
			$("#search_lightbox_form1 :input[name=inyear]").val(inyear);
			$("#search_lightbox_form1 :input[name=fullcheckin]").val(chkin);
			
			var chkout = $("#search_form_main :input[name=fullcheckout]").val()
			var val2 = chkout.split('/');
			outday    = Number(val2[1]);
			outmonth  = Number(val2[0]);
			outyear   = Number(val2[2])>2000?Number(val2[2]):2000+Number(val2[2]);
			outmonth=outmonth<10?"0"+outmonth:outmonth;
			$("#search_lightbox_form1 :input[name=outmonth]").val(outmonth);
			$("#search_lightbox_form1 :input[name=outday]").val(outday);
			$("#search_lightbox_form1 :input[name=outyear]").val(outyear);
			$("#search_lightbox_form1 :input[name=fullcheckout]").val(chkout);
			
			// Unset total images in imageArray
			settings.imageArray.length = 0;
			// Unset image active information
			settings.activeImage = 0;
			// We have an image set? Or just an image? Let´s see it.
			if ( jQueryMatchedObj.length == 1 ) {
				settings.imageArray.push(new Array(objClicked.getAttribute('link'),objClicked.getAttribute('title')));
			} else {
				// Add an Array (as many as we have), with href and title atributes, inside the Array that storage the images references
				for ( var i = 0; i < jQueryMatchedObj.length; i++ ) {
				    settings.imageArray.push(new Array(jQueryMatchedObj[i].getAttribute('link'),jQueryMatchedObj[i].getAttribute('title')));
				}
			}
			while ( settings.imageArray[settings.activeImage][0] != objClicked.getAttribute('link') ) {
				settings.activeImage++;
			}
			// Call the function that prepares image exibition
			_set_image_to_view();
		}
		/**
		 * Create the jQuery lightBox plugin interface
		 *
		 * The HTML markup will be like that:
			<div id="jquery-overlay"></div>
			<div id="jquery-lightbox">
				<div id="lightbox-container-image-box">
					<div id="lightbox-container-image">
						<img src="../fotos/XX.jpg" id="lightbox-image">
						<div id="lightbox-nav">
							<a href="#" id="lightbox-nav-btnPrev"></a>
							<a href="#" id="lightbox-nav-btnNext"></a>
						</div>
						<div id="lightbox-loading">
							<a href="#" id="lightbox-loading-link">
								<img src="../images/lightbox-ico-loading.gif">
							</a>
						</div>
					</div>
				</div>
				<div id="lightbox-container-image-data-box">
					<div id="lightbox-container-image-data">
						<div id="lightbox-image-details">
							<span id="lightbox-image-details-caption"></span>
							<span id="lightbox-image-details-currentNumber"></span>
						</div>
						<div id="lightbox-secNav">
							<a href="#" id="lightbox-secNav-btnClose">
								<img src="../images/lightbox-btn-close.gif">
							</a>
						</div>
					</div>
				</div>
			</div>
		 *
		 */
		function _set_interface() {
			// Apply the HTML markup into body tag
			$('body').append('<div id="jquery-overlay"></div><div id="jquery-lightbox"><div id="lightbox-container-image-box"><div id="lightbox-container-image"><img id="lightbox-image"><div style="" id="lightbox-nav"><a href="#" id="lightbox-nav-btnPrev"></a><a href="#" id="lightbox-nav-btnNext"></a></div><div id="lightbox-loading"><a href="#" id="lightbox-loading-link"><img src="' + settings.imageLoading + '"></a></div></div></div><div id="lightbox-container-image-data-box"><div id="lightbox-searchform"></div><div id="lightbox-container-image-data"><div id="lightbox-image-details"><span id="lightbox-image-details-caption"></span><span id="lightbox-image-details-currentNumber"></span></div><div id="lightbox-secNav"><a href="#" id="lightbox-secNav-btnClose"><img src="' + settings.imageBtnClose + '"></a></div></div></div></div>');
			var search_form_str=$('#id_search_form').html();
			search_form_str=search_form_str.replace(/__DYNAMIC_NAME/g, "_form1");
			//search_lightbox__DYNAMIC_NAME
			$('#lightbox-searchform').html(search_form_str);
			// Get page sizes
			var arrPageSizes = ___getPageSize();
			// Style overlay and show it
			$('#jquery-overlay').css({
				backgroundColor:	settings.overlayBgColor,
				opacity:			settings.overlayOpacity,
				width:				arrPageSizes[0],
				height:				arrPageSizes[1]
			}).fadeIn();
			// Get page scroll
			var arrPageScroll = ___getPageScroll();
			// Calculate top and left offset for the jquery-lightbox div object and show it
			$('#jquery-lightbox').css({
				top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
				left:	arrPageScroll[0]
			}).show();
			// Assigning click events in elements to close overlay
			$('#jquery-overlay').click(function() {
				_finish();
			});
			// Assign the _finish function to lightbox-loading-link and lightbox-secNav-btnClose objects
			$('#lightbox-loading-link,#lightbox-secNav-btnClose').click(function() {
				_finish();
				return false;
			});

//			$('#lightbox-searchform').click(function() {
//			    //alert('Ravi wins');
//			    return false;
//				//_finish();
//			});
			// If window was resized, calculate the new overlay dimensions
			$(window).resize(function() {
				// Get page sizes
				var arrPageSizes = ___getPageSize();
				// Style overlay and show it
				$('#jquery-overlay').css({
					width:		arrPageSizes[0],
					height:		arrPageSizes[1]
				});
				// Get page scroll
				var arrPageScroll = ___getPageScroll();
				// Calculate top and left offset for the jquery-lightbox div object and show it
				$('#jquery-lightbox').css({
					top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
					left:	arrPageScroll[0]
				});
			});
		}
		/**
		 * Prepares image exibition; doing a image´s preloader to calculate it´s size
		 *
		 */
		function _set_image_to_view() { // show the loading
			// Show the loading
			$('#lightbox-loading').show();
			if ( settings.fixedNavigation ) {
				$('#lightbox-image,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();
			} else {
				// Hide some elements
				$('#lightbox-image,#lightbox-nav,#lightbox-nav-btnPrev,#lightbox-nav-btnNext,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();
			}
			// Image preload process
			var objImagePreloader = new Image();
			objImagePreloader.onload = function() {
				$('#lightbox-image').attr('src',settings.imageArray[settings.activeImage][0]);
				// Perfomance an effect in the image container resizing it
				_resize_container_image_box(objImagePreloader.width,objImagePreloader.height);
				//	clear onLoad, IE behaves irratically with animated gifs otherwise
				objImagePreloader.onload=function(){};
			};

			if(settings.imageArray[settings.activeImage] != undefined)
			{
			     objImagePreloader.src = settings.imageArray[settings.activeImage][0];
			    //$('#lightbox-image').attr('src',settings.imageArray[settings.activeImage][0]);
			}
		};
		/**
		 * Perfomance an effect in the image container resizing it
		 *
		 * @param integer intImageWidth The image´s width that will be showed
		 * @param integer intImageHeight The image´s height that will be showed
		 */
		function _resize_container_image_box(intImageWidth,intImageHeight) {
			// Get current width and height
			var intCurrentWidth = $('#lightbox-container-image-box').width();
			var intCurrentHeight = $('#lightbox-container-image-box').height();
			// Get the width and height of the selected image plus the padding
			var intWidth = (intImageWidth + (settings.containerBorderSize * 2)); // Plus the image´s width and the left and right padding value
			var intHeight = (intImageHeight + (settings.containerBorderSize * 2)); // Plus the image´s height and the left and right padding value
			// Diferences
			var intDiffW = intCurrentWidth - intWidth;
			var intDiffH = intCurrentHeight - intHeight;
			// Perfomance the effect
			$('#lightbox-container-image-box').animate({ width: intWidth, height: intHeight },settings.containerResizeSpeed,function() { _show_image(); });
			if ( ( intDiffW == 0 ) && ( intDiffH == 0 ) ) {
				if ( $.browser.msie ) {
					___pause(250);
				} else {
					___pause(100);
				}
			}
			$('#lightbox-container-image-data-box').css({ width: intImageWidth });
			$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ height: intImageHeight + (settings.containerBorderSize * 2) });
		};
		/**
		 * Show the prepared image
		 *
		 */
		function _show_image() {
			$('#lightbox-loading').hide();
			$('#lightbox-image').fadeIn(function() {
				_show_image_data();
				_set_navigation();
			});
			_preload_neighbor_images();
		};
		/**
		 * Show the image information
		 *
		 */
		function _show_image_data() {
			$('#lightbox-container-image-data-box').slideDown('fast');
			$('#lightbox-image-details-caption').hide();

			if ( settings.imageArray[settings.activeImage][1] ) {
				$('#lightbox-image-details-caption').html(settings.imageArray[settings.activeImage][1]).show();
			}
			// If we have a image set, display 'Image X of X'
			if ( settings.imageArray.length > 1 ) {
				$('#lightbox-image-details-currentNumber').html(settings.txtImage + ' ' + ( settings.activeImage + 1 ) + ' ' + settings.txtOf + ' ' + settings.imageArray.length).show();
			}
		}
		/**
		 * Display the button navigations
		 *
		 */
		function _set_navigation() {
			$('#lightbox-nav').show();

			//alert(settings.activeImage);
			// Instead to define this configuration in CSS file, we define here. And it´s need to IE. Just.
			//$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });

			// Show the prev button, if not the first image in set
			if ( settings.activeImage != 0 ) {
				if ( settings.fixedNavigation ) {
					$('#lightbox-nav-btnPrev').css({ 'background' : 'url(' + settings.imageBtnPrev + ') left 15% no-repeat' })
						.unbind()
						.bind('click',function() {
							settings.activeImage = settings.activeImage - 1;
							if(settings.activeImage <0 )
							{
							  settings.activeImage = settings.imageArray.length - 1;
							}
							    _set_image_to_view();
							    return false;

						});
				} else {
					// Show the images button for Next buttons
					$('#lightbox-nav-btnPrev').unbind().hover(function() {
						$(this).css({ 'background' : 'url(' + settings.imageBtnPrev + ') left 15% no-repeat' });
					},function() {
						$(this).css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });
					}).show().bind('click',function() {
						settings.activeImage = settings.activeImage - 1;
						_set_image_to_view();
						return false;
					});
				}
			}

			// Show the next button, if not the last image in set
			if ( settings.activeImage != ( settings.imageArray.length -1 ) ) {
				if ( settings.fixedNavigation ) {
					$('#lightbox-nav-btnNext').css({ 'background' : 'url(' + settings.imageBtnNext + ') right 15% no-repeat' })
						.unbind()
						.bind('click',function() {
							settings.activeImage = settings.activeImage + 1;
                            if(settings.activeImage == (settings.imageArray.length))
							{
							    settings.activeImage = 0;
							}
							/*if(settings.activeImage == (settings.imageArray.length-1))
							{
							    $('#lightbox-nav-btnNext').hide();
							}
							if(settings.activeImage < settings.imageArray.length)
							{*/
							    _set_image_to_view();
							    return false;
							/*}*/
						});
				} else {
					// Show the images button for Next buttons
					$('#lightbox-nav-btnNext').unbind().hover(function() {
						$(this).css({ 'background' : 'url(' + settings.imageBtnNext + ') right 15% no-repeat' });
					},function() {
						$(this).css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });
					}).show().bind('click',function() {
						settings.activeImage = settings.activeImage + 1;
						_set_image_to_view();
						return false;
					});
				}
			}
			// Enable keyboard navigation
			_enable_keyboard_navigation();
		}
		/**
		 * Enable a support to keyboard navigation
		 *
		 */
		function _enable_keyboard_navigation() {
			$(document).keydown(function(objEvent) {
				_keyboard_action(objEvent);
			});
		}
		/**
		 * Disable the support to keyboard navigation
		 *
		 */
		function _disable_keyboard_navigation() {
			$(document).unbind();
		}
		/**
		 * Perform the keyboard actions
		 *
		 */
		function _keyboard_action(objEvent) {
			// To ie
			if ( objEvent == null ) {
				keycode = event.keyCode;
				escapeKey = 27;
			// To Mozilla
			} else {
				keycode = objEvent.keyCode;
				escapeKey = objEvent.DOM_VK_ESCAPE;
			}
			// Get the key in lower case form
			key = String.fromCharCode(keycode).toLowerCase();
			// Verify the keys to close the ligthBox
			if ( ( key == settings.keyToClose ) || ( key == 'x' ) || ( keycode == escapeKey ) ) {
				_finish();
			}
			// Verify the key to show the previous image
			if ( ( key == settings.keyToPrev ) || ( keycode == 37 ) ) {
				// If we´re not showing the first image, call the previous
				if ( settings.activeImage != 0 ) {
					settings.activeImage = settings.activeImage - 1;
					_set_image_to_view();
					_disable_keyboard_navigation();
				}
			}
			// Verify the key to show the next image
			if ( ( key == settings.keyToNext ) || ( keycode == 39 ) ) {
				// If we´re not showing the last image, call the next
				if ( settings.activeImage != ( settings.imageArray.length - 1 ) ) {
					settings.activeImage = settings.activeImage + 1;
					_set_image_to_view();
					_disable_keyboard_navigation();
				}
			}
		}
		/**
		 * Preload prev and next images being showed
		 *
		 */
		function _preload_neighbor_images() {
		    if ( (settings.imageArray.length -1) > settings.activeImage ) {
				objNext = new Image();
				objNext.src = settings.imageArray[settings.activeImage + 1][0];
			}
			if ( settings.activeImage > 0 ) {
				objPrev = new Image();
				objPrev.src = settings.imageArray[settings.activeImage -1][0];
			}
		}
		/**
		 * Remove jQuery lightBox plugin HTML markup
		 *
		 */
		function _finish() {
			$('#jquery-lightbox').remove();
			$('#jquery-overlay').fadeOut(function() { $('#jquery-overlay').remove(); });
			// Show some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
			//$('embed, object, select').css({ 'visibility' : 'visible' });
			$("#search_form_main :input[name=inday]").css({ 'visibility' : 'visible' });
			$("#search_form_main :input[name=inmonth]").css({ 'visibility' : 'visible' });
			$("#search_form_main :input[name=inyear]").css({ 'visibility' : 'visible' });
			$("#search_form_main :input[name=outday]").css({ 'visibility' : 'visible' });
			$("#search_form_main :input[name=outmonth]").css({ 'visibility' : 'visible' });
			$("#search_form_main :input[name=outyear]").css({ 'visibility' : 'visible' });
			$("#search_form_main :input[name=search_area]").css({ 'visibility' : 'visible' });
			$('#lm_type,#numrooms').css({ 'visibility' : 'visible' });
		}
		/**
		 / THIRD FUNCTION
		 * getPageSize() by quirksmode.com
		 *
		 * @return Array Return an array with page width, height and window width, height
		 */
		function ___getPageSize() {
			var xScroll, yScroll;
			if (window.innerHeight && window.scrollMaxY) {
				xScroll = window.innerWidth + window.scrollMaxX;
				yScroll = window.innerHeight + window.scrollMaxY;
			} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
				xScroll = document.body.scrollWidth;
				yScroll = document.body.scrollHeight;
			} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
				xScroll = document.body.offsetWidth;
				yScroll = document.body.offsetHeight;
			}
			var windowWidth, windowHeight;
			if (self.innerHeight) {	// all except Explorer
				if(document.documentElement.clientWidth){
					windowWidth = document.documentElement.clientWidth;
				} else {
					windowWidth = self.innerWidth;
				}
				windowHeight = self.innerHeight;
			} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
				windowWidth = document.documentElement.clientWidth;
				windowHeight = document.documentElement.clientHeight;
			} else if (document.body) { // other Explorers
				windowWidth = document.body.clientWidth;
				windowHeight = document.body.clientHeight;
			}
			// for small pages with total height less then height of the viewport
			if(yScroll < windowHeight){
				pageHeight = windowHeight;
			} else {
				pageHeight = yScroll;
			}
			// for small pages with total width less then width of the viewport
			if(xScroll < windowWidth){
				pageWidth = xScroll;
			} else {
				pageWidth = windowWidth;
			}
			arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
			return arrayPageSize;
		};
		/**
		 / THIRD FUNCTION
		 * getPageScroll() by quirksmode.com
		 *
		 * @return Array Return an array with x,y page scroll values.
		 */
		function ___getPageScroll() {
			var xScroll, yScroll;
			if (self.pageYOffset) {
				yScroll = self.pageYOffset;
				xScroll = self.pageXOffset;
			} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
				yScroll = document.documentElement.scrollTop;
				xScroll = document.documentElement.scrollLeft;
			} else if (document.body) {// all other Explorers
				yScroll = document.body.scrollTop;
				xScroll = document.body.scrollLeft;
			}
			arrayPageScroll = new Array(xScroll,yScroll);
			return arrayPageScroll;
		};
		 /**
		  * Stop the code execution from a escified time in milisecond
		  *
		  */
		 function ___pause(ms) {
			var date = new Date();
			curDate = null;
			do { var curDate = new Date(); }
			while ( curDate - date < ms);
		 };
		// Return the jQuery object for chaining. The unbind method is used to avoid click conflict when the plugin is called more than once
		return this.unbind('click').click(_initialize);
	};
})(jQuery); // Call and execute the function immediately passing the jQuery object

// Function to show post new reviews form
function reviewForm(frmId)
{document.getElementById(frmId).style.display='';}
// Function to set value for page(previous, next, last) and submit the review form
function getPage(page,div){
// only tab space overlay
ch= $('#tab_content').height();
cw = $('#tab_content').width();
var divpos = $('#tab_content').offset();
ct = divpos.top;cl = divpos.left;
$('#ajax_loading_overlay').css({width:cw,height:ch,top:ct,left:cl,display:'block'});
$('#ajax_loading_image').css({top:ct+50,left:cl+(cw/3)+80,display:'block'});
$.ajax({
	url: '/hotel_reviews.php',
	data: 'page='+page,
	success: function(data) {
	    $(document).scrollTop(0);
	    $("#ajax_loading_overlay").css('display','none');
		$("#ajax_loading_image").css('display','none');
	    $('#'+div).html(data);
	}});
}
// To submt form
function submit_review(div,limit_first,limit_last){
var guest_name = $("#guest_name").val();
var comment = $("#comment").val();
var guest_email = $("#guest_email").val();
var overall_rating = $("#overall_rating").val();
var hotel_service = $("#hotel_service").val();
var hotel_condition = $("#hotel_condition").val();
var room_comfort = $("#room_comfort").val();
var room_cleanliness = $("#room_cleanliness").val();
if(guest_name=='')
{alert('Please enter the name');return;}
if(comment=='')
{alert('Please enter the comment');return;}
$.ajax({
	type: 'POST',
    url: '/hotel_reviews.php',
	data: 'guest_name='+guest_name+'&comment='+comment+'&guest_email='+guest_email+'&overall_rating='+overall_rating+'&hotel_service='+hotel_service+'&hotel_condition='+hotel_condition+'&room_comfort='+room_comfort+'&room_cleanliness='+room_cleanliness+'&first='+limit_first+'&last='+limit_last,
	success: function(data) {
	$(document).scrollTop(0);
	$('#'+div).html(data);
	    }
	});
}
// Function to close review form
function closeReview(frmId)
{document.getElementById(frmId).style.display='none';}
function alterContent(show_id, hide_id){
var show=document.getElementById(show_id);
var hide=document.getElementById(hide_id);
hide.style.display='none';
show.style.display='block';
if(show.id == 'hotel_air')
{
	document.getElementById('table_search').className='SearchForm_solidbackgroundcolor';
	document.getElementById('tr_air').style.display='block';
	document.getElementById('check_in_out').style.display='none';
}else{
	// change class to image only if room selected is one - to prevent image repeat
	if(document.getElementById('numrooms').value == 1)
	{document.getElementById('table_search').className='SearchForm_BackgroundImage';}
	document.getElementById('tr_air').style.display='none';
	document.getElementById('check_in_out').style.display='block';
	document.getElementById('child_desc').style.display='none';
}}
function showHideContent(val){var doc=document.getElementById(val);doc.style.display='block';}
function showHideDiv(val){var doc=document.getElementById(val);if(doc){doc.style.display=(doc.style.display=='none')?'block':'none';}}
function showHideContentTab(show,hide1,hide2,hide3){
document.getElementById(show+"_tab").className="class_"+show+"_off";
document.getElementById(hide1+"_tab").className="class_"+hide1;
document.getElementById(hide2+"_tab").className="class_"+hide2;
document.getElementById(hide3+"_tab").className="class_"+hide3;
document.getElementById(show).style.display='block';
document.getElementById(hide1).style.display='none';
document.getElementById(hide2).style.display='none';
document.getElementById(hide3).style.display='none';
}
function add_room(num,div_id,child_div){
document.getElementById('table_search').className='SearchForm_solidbackgroundcolor';
document.getElementById('adult_def').style.display='none';document.getElementById('child_def').style.display='none';
document.getElementById('adult_lab').style.display='none';document.getElementById('child_lab').style.display='none';
document.getElementById('child_desc').style.display='none';
var result = "<div id='roombox'><table width='100%' border='0' cellspacing='0' cellpadding='0'>";
if(num>1){
	var childDIVs = "";
	for(var i=1;i<=num;i++){
		childDIVs = childDIVs+"<div id=child"+i+"></div>";
		result = result+"<tr><td height='17' width='34%' class='SearchForm_LabelFont'></td><td height='17' width='33%' class='SearchForm_smallfont' align='left' style='padding-left:1px;'>Adults:</td><td height='17' align='left' style='padding-left:4px;'  width='33%' class='SearchForm_smallfont'>Children:</td></tr><tr><td height='17' width='34%' class='SearchForm_LabelFont'>Room"+i+":</td><td height='17' width='33%' align='left' class='SearchForm_LabelFont'><select name='menu3' class='SearchForm_inputbox12pixel'><option> 1 </option><option> 2 </option><option> 3 </option></select></td><td height='17' width='33%' align='right' class='SearchForm_LabelFont'><select name='menu4' class='SearchForm_inputbox12pixel' onchange='add_child(this.value, \"child"+i+"\", \"Room"+i+"\", \"child\");'><option> 0 </option><option> 1 </option><option> 2 </option>  </select></td></tr>";
	}
	result = result+"</table></div>";
}else{
	document.getElementById('adult_def').style.display='block';document.getElementById('child_def').style.display='block';
	document.getElementById('adult_lab').style.display='block';document.getElementById('child_lab').style.display='block';
	// prevent undefined display
	document.getElementById('child').style.display='none';
	// reset original class
	document.getElementById('table_search').className='SearchForm_BackgroundImage';
}
document.getElementById(div_id).innerHTML = result;
document.getElementById(child_div).innerHTML = childDIVs;
document.getElementById(div_id).style.display='block';
}
function add_child(num,div_id,room,child){
var result = "<table width='100%' border='0' cellspacing='0' cellpadding='0'><tr><td align='right'><table width='100%' border='0' cellspacing='0' cellpadding='0'><tr><td height='17'  class='SearchForm_smallfont'></td>";
for(var i=1;i<=num;i++){
	result = result+"<td height='19'  align='left'  class='SearchForm_smallfont'>Child"+i+":</td>";
}
result = result+"</tr><tr><td height='17' width='63px' class='SearchForm_LabelFont'>"+room+"</td>";
for(var i=1;i<=num;i++){
	result = result+"<td height='17' align='left'  class='SearchForm_LabelFont'><select name='menu3' style='font-size:12px; font-family:Arial; color:#000000;'><option> ? </option><option> 0-2 </option><option> 2-11 </option></select></td>";
}
result = result+"</tr></table></td></tr></table>";
document.getElementById(div_id).innerHTML = result;
document.getElementById(child).style.display='block';
document.getElementById('child_desc').style.display='block';
}
function MM_jumpMenu(targ,selObj,restore){ //v3.0
eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
if (restore) selObj.selectedIndex=0;
}
var style_cookie_name = "style";
var style_cookie_duration = 30;
function set_style_from_cookie()
{var css_title=get_cookie(style_cookie_name);if(css_title.length){switch_style(css_title);}}
function set_cookie(cookie_name,cookie_value,lifespan_in_days,valid_domain){
// http://www.thesitewizard.com/javascripts/cookies.shtml
var domain_string = valid_domain ?
("; domain=" + valid_domain) : '' ;
document.cookie = cookie_name +
"=" + encodeURIComponent( cookie_value ) +
"; max-age=" + 60 * 60 *
24 * lifespan_in_days +
"; path=/" + domain_string ;
}
function get_cookie(cookie_name){
// http://www.thesitewizard.com/javascripts/cookies.shtml
var cookie_string = document.cookie ;
if (cookie_string.length != 0) {
	var cookie_value = cookie_string.match (
	'(^|;)[\s]*' +
	cookie_name +
	'=([^;]*)' );
	return decodeURIComponent ( cookie_value[2] ) ;
}
return '' ;
}
function openWin(url,h,w,t,l){newWin = window.open(url,'','top='+t+',left='+l+',scrollbars=no,location=no,status=no,width='+w+'height='+h);newWin.resizeTo(w+10,h+50);}
function openWinS(url,h,w,t,l){newWin = window.open(url,'','top='+t+',left='+l+',scrollbars=yes,location=no,status=no,width='+w+'height='+h);newWin.resizeTo(w+5,h+50);}
function openWinMy(url,h,w,t,l){
	var centeredY,centeredX;
	if ($.browser.msie) {//hacked together for IE browsers
		centeredY = (window.screenTop - 120) + ((((document.documentElement.clientHeight + 120)/2) - (h/2)));
		centeredX = window.screenLeft + ((((document.body.offsetWidth + 20)/2) - (w/2)));
	}else{
		centeredY = window.screenY + (((window.outerHeight/2) - (h/2)));
		centeredX = window.screenX + (((window.outerWidth/2) - (w/2)));
	}
	newWin = window.open(url,'','top='+centeredY+',left='+centeredX+',scrollbars=no,location=no,status=no,width='+w+',height='+h);
}
/***********************************************
* Bookmark site script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
/* Modified to support Opera */
function bookmarksite(title,url){
if (window.sidebar) // firefox
window.sidebar.addPanel(title, url, "");
else if(window.opera && window.print){ // opera
	var elem = document.createElement('a');
	elem.setAttribute('href',url);
	elem.setAttribute('title',title);
	elem.setAttribute('rel','sidebar');
	elem.click();
}
else if(document.all)// ie
window.external.AddFavorite(url, title);
}
// Booking form javascript functions
// Function to save fields of booking form.
function savefields(whichform)
{
var bookform = document.getElementById("bookingform");
var genericarray = new Object;
for (i=0;i<bookform.elements.length;i++)
{
	var fname = bookform.elements[i].name;
	var fvalue = bookform.elements[i].value;
	var ftype = bookform.elements[i].type;
	var vname = "";
	if (ftype != 'hidden' && ftype != 'submit'){
		if (strpos(fname,"[]",0) > 0){
		vname = fname.replace(/\[\]/, "")
		if (!genericarray[vname]) genericarray[vname] = 0;
		fname = fname.replace(/\[\]/, "["+genericarray[vname]+"]");
		genericarray[vname] ++;
		}
		addfield(fname,whichform,fvalue);
	}
}}
// Function to get string position.
function strpos(haystack,needle,offset){
// http://kevin.vanzonneveld.net
// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// *     example 1: strpos('Kevin van Zonneveld', 'e', 5);
// *     returns 1: 14
var i = haystack.indexOf( needle, offset ); // returns -1
return i >= 0 ? i : false;
}
// Function to add more fields on change of number of rooms on booking page.
function addfield(field,area,value){
var field_area = document.getElementById(area);
var input = document.createElement("input");
input.name = field;
input.value = value;
input.type = "hidden"; //Type of field - can be any valid input type like text,file,checkbox etc.
field_area.appendChild(input);
}
// Function to show and hide layer on booking page.
var state = 'none';
function showhide(layer_ref){
if (state == 'block'){state = 'none';}else{state = 'block';}
if (document.all) { //IS IE 4 or 5 (or 6 beta)
	eval( "document.all." + layer_ref + ".style.display = state");
}
if (document.layers) { //IS NETSCAPE 4 or below
	document.layers[layer_ref].display = state;
}
if (document.getElementById &&!document.all) {
	hza = document.getElementById(layer_ref);
	hza.style.display = state;
}
}
// to get the current scroll position
function ___getPageScroll() {
var xScroll, yScroll;
if (self.pageYOffset) {
	yScroll = self.pageYOffset;
	xScroll = self.pageXOffset;
} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
	yScroll = document.documentElement.scrollTop;
	xScroll = document.documentElement.scrollLeft;
} else if (document.body) {// all other Explorers
	yScroll = document.body.scrollTop;
	xScroll = document.body.scrollLeft;
}
arrayPageScroll = new Array(xScroll,yScroll);
return arrayPageScroll;
};
function ___getPageSize() {
var xScroll, yScroll;
if (window.innerHeight && window.scrollMaxY) {
	xScroll = window.innerWidth + window.scrollMaxX;
	yScroll = window.innerHeight + window.scrollMaxY;
} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
	xScroll = document.body.scrollWidth;
	yScroll = document.body.scrollHeight;
} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
	xScroll = document.body.offsetWidth;
	yScroll = document.body.offsetHeight;
}
var windowWidth, windowHeight;
if (self.innerHeight) {	// all except Explorer
	if(document.documentElement.clientWidth){
		windowWidth = document.documentElement.clientWidth;
	} else {
		windowWidth = self.innerWidth;
	}
	windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
	windowWidth = document.documentElement.clientWidth;
	windowHeight = document.documentElement.clientHeight;
} else if (document.body) { // other Explorers
	windowWidth = document.body.clientWidth;
	windowHeight = document.body.clientHeight;
}
// for small pages with total height less then height of the viewport
if(yScroll < windowHeight){
	pageHeight = windowHeight;
} else {
	pageHeight = yScroll;
}
// for small pages with total width less then width of the viewport
if(xScroll < windowWidth){
	pageWidth = xScroll;
} else {
	pageWidth = windowWidth;
}
arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
return arrayPageSize;
};
function changetotalrate(id,value){
if(document.getElementById(id))document.getElementById(id).innerHTML=value;}
function showRateDetailsall(hotn_id,div_id,type){
var disp=$('#'+div_id).css('display');
if(disp=='block'){
	mySlider('rate',div_id);
}else{
mySlider('rate',div_id);
$.ajax({
	url: "/RateDetailsAll/"+hotn_id,
	success: function(html){
//		$('#'+div_id).css('display','none');
		$('#td_'+div_id).html(html);
	}
});
}}
function showRateDetails(hotn_id,div_id,t,sessionid){
var disp=$('#'+div_id).css('display');
if(disp=='block'){
    mySlider('rate',div_id);
}else{
    mySlider('rate',div_id);
    if($('#td_'+div_id).html().length<100){
        $.ajax({
            url: "/RateDetails/"+t+"/"+hotn_id,
            type: "GET",
            data: "sessionid="+sessionid,
            success: function(html){
                if(html.indexOf('SESSION-EXPIRED-ERROR')>=0){
                	window.location.reload(true);
                    //alert('Your session has expired due to inactivity. Please refresh the page.');
                    return;
                }
                //		$('#'+div_id).css('display','none');
                $('#td_'+div_id).html(html);
            }
        });
    }
}}
function showRateDetailsSub(hotn_id,div_id,t,sessionid){
/*if(type=='main' && $('#'+div_id).css('display')=='block'){
    mySlider('rate',div_id);
}else{
    if(type=='main' && $('#td_'+div_id).html().length>100){
        mySlider('rate',div_id);
    }else{
    if(type!='sub'){
        mySlider('rate',div_id);
    }*/
    $.ajax({
        url: "/RateDetails/"+t+"/"+hotn_id,
        type: "GET",
        data: "sessionid="+sessionid,
        success: function(html){
            if(html.indexOf('SESSION-EXPIRED-ERROR')>=0){
                //alert('Your session has expired due to inactivity. Please refresh the page.');
                return;
            }
            //		$('#'+div_id).css('display','none');
            $('#td_'+div_id).html(html);
        }
    });
//        }
//    }
}
function showPromoDetails(promoID,div_id,sessionid){
var disp=$('#'+div_id).css('display');
if(disp=='block'){
	mySlider('promo',div_id);
}else{
	mySlider('promo',div_id);
$.ajax({
	url: "/PromoDetails/"+promoID,
	type: "GET",
	data: "sessionid="+sessionid,
	success: function(html){
		$('#td_'+div_id).html(html);
	}
});
}
}
function showSearchForm(searchFormId,div_id){
var disp=$('#'+div_id).css('display');
if(disp=='block'){$('#'+searchFormId).css('display','none');}
}
function sortPromoSidebar(sortby,area,div_id,cond){
if(area=='')area=0;
if(cond=='')cond=0;
$.ajax({
	url: "/promosidebarsort/"+sortby+"/"+area+"/"+cond+"/",
	success: function(html){
		$('#'+div_id).html(html);
	}
});
}
function expandArea(id,property,extra){
var val = $(id).css(property);
if(val=='auto' && property=='height'){  // IE fix to prevent js error
	val = '0px' // set zero default
	extra = default_height;
}
val = val.replace(/px/g,'');
val = Number(val) + extra;
$(id).css(property,val);
}
function AdjustCityPage(){
var actual_height= $("#city_hotellist").css("height");
//alert(actual_height);
if(actual_height=='auto'){  // IE fix to prevent js error
	actual_height = $("#city_hotellist").height(); // get height with out px value
}else{
	actual_height = actual_height.replace(/px/g,'');
}
//alert(actual_height);
var addtop = 495;
// if IE, make adjustments in the top positions
if ( $.browser.msie ) {
  var b = (parseInt($.browser.version ));
  	expandArea("#city_hotellist","top",-1);
  addtop--;
}
// for dynamic content height based adjustment
content_height = $("#city_content").height();
var c = Number($("#city_content").css("top").replace(/px/g,'')) + content_height;
var d = c - Number($("#city_hotellist").css("top").replace(/px/g,''));
expandArea("#city_hotellist","top",d);
var extra = Number(actual_height) + addtop + d;
expandArea("#content_container_box4","top",extra);
}
function AdjustAreaPage(){
var actual_height= $("#content_text").css("height");
//alert(actual_height);
if(actual_height=='auto'){  // IE fix to prevent js error
	actual_height = $("#content_text").height(); // get height with out px value
}else{
	actual_height = actual_height.replace(/px/g,'');
}
//alert(actual_height);
if(actual_height > default_height){
	var extra = Number(actual_height) - default_height;
	expandArea("#Content-Footer-Margin_","top",extra);
	expandArea("#Content-Map-Margin_","height",extra);
	expandArea("#Left-Vert-Margin_","height",extra);
	expandArea("#Right-Vert-Margin_","height",extra);
	expandArea("#Map_","height",extra);
	expandArea("#Map-Footer-Margin_","top",extra);
	expandArea("#Footer_","top",extra);
	expandArea("#Bottom-AreaHotels_","top",extra);
}else{
	var extra = default_height - Number(actual_height);
	expandArea("#content_text","height",extra);
}}
function reStoremorediv(){
$('#more_span').css('display','none');

setTimeout("javascript:document.getElementById('moretext107300').style.display='none',$('#more_span').css('display','inline');", 10000);
}
var curr_loc = location.href.split('#');
if(typeof(curr_loc[1]) != "undefined"){
	if(curr_loc[1].indexOf('_')!=-1){
		curr_loc=curr_loc[1].split('_');
		curr_loc = curr_loc[1].substring(0,4);
	}else{
		curr_loc = curr_loc[1].substring(0,4);
	}
	if(typeof(curr_loc)!= "undefined"){
		if(curr_loc!=''){
			$.ajax({url: "/AgentChange/?specialid="+curr_loc+'&link='+location.href});
		}
	}
}
function changeCurrencyPage(cur){ $('#switchlangimg').css('display','inline'); cur.form.tag.value='hotel_search_lang_'+cur.value;
cur.form.submit(); }
function checkAmenity(amenity_value,id){
if($("#"+id).is(':checked') == true) { var pre_val = $("#amenity_value").val(); 
var new_val = amenity_value; $("#amenity_value").val(pre_val+":::"+new_val); 
} else { var pre_val = $("#amenity_value").val(); var new_val = pre_val.replace(":::"+amenity_value, ""); 
$("#amenity_value").val(new_val); } 
} 
// Function used to select all amenity 
function check_all(counter){
$("INPUT[@name=amenity_section][type='checkbox']").attr('checked', true); $("#amenity_value").val(""); 
for(var i=1;i<counter;i++) 
{ 
	id="amenity_"+i; 
	if($("#"+id).is(':checked') == true) 
	{ 	var pre_val = $("#amenity_value").val(); var new_val = $("#"+id).val();
		$("#amenity_value").val(pre_val+":::"+new_val); 
	} 
}} 
// To uncheck all checked amenities 
function unCheck_all(){ $("INPUT[@name=amenity_section][type='checkbox']").attr('checked', false); $("#amenity_value").val(""); } 


function mySlider(type,id){
	var imgsrc='';
	if($('#'+id).css('display')=='none'){
		$('#'+id).slideDown("slow");
		imgsrc="minus.gif";
	}else{
		$('#'+id).slideUp("slow");
		imgsrc="plus.gif";
	}
	// check which slider to open
	if(type=='promo'){
		id = id.replace(/promo/g,'');
		// if images found, toggle +- sign
		if($('#'+'promoimg'+id)){$('#'+'promoimg'+id).attr("src","/img/i4content/"+imgsrc);}
		if($('#'+'promoimg2'+id)){$('#'+'promoimg2'+id).attr("src","/img/i4content/"+imgsrc);}
	}
	if(type=='rate'){
		id = id.replace(/rate/g,'');
		if($('#'+'rateimg'+id)){$('#'+'rateimg'+id).attr("src","/img/i4content/"+imgsrc);}
	}
}
$(function(){$('a.lightbox').lightBox({fixedNavigation:true}); });
function showWait(){
	//waitPage ='{include file=waitpage.tpl}';		// code moved in search form tpl
	Mac = navigator.userAgent.indexOf("Mac") != -1;
	Msie = navigator.userAgent.indexOf("MSIE") != -1;
	if (!(Mac && Msie)) {
		if (document.documentElement && document.all)
		document.body.innerHTML = waitPage;
		else if (document.all)
		document.body.innerHTML = waitPage;
		else if (document.getElementById)
		document.documentElement.innerHTML = waitPage;
		else if (contentDocument)
		contentDocument.body.innerHTML  = waitPage
	}
	if(document.body!=null){
		// set the background white and remove any background image
		document.body.style.backgroundColor='#ffffff';
		document.body.style.backgroundImage="none";
	}
	//cw = setInterval('checkwait()',1000);
}
var waitduration=1;
function checkwait(){
	if(waitduration>=10){
		if(confirm("Problem connecting to the secure page, please refresh current page.\n\n NOTE : If you are using IE and get Security Alert - 'You are about to view pages over a Secure Connection' \n on that prompt click OK button to continue. \n\nRefresh Current Page ?"))
		window.location.reload();
		waitduration=0;
	}
	waitduration++;
}
function showWaitD(){
	// IE6 does not understand position:fixed !!
	if ($.browser.msie && $.browser.version=='6.0'){
		setTimeout('showWait()', 500);	// page body replace style only for IE6
	}else{	// for others show a div for wait page
		//var arrPageScroll = ___getPageScroll();
		// Calculate top and left offset for waitpage div object and show it
		var arrPageSizes = ___getPageSize();
		/*top:	arrPageScroll[1] ,
		left:	arrPageScroll[0] ,
		*/
		$('#ajax_waitpage').css({top:0,left:0,display:'block',position:'fixed'});
	    $('#ajax_waitpage_overlay').css({width:arrPageSizes[0],height:arrPageSizes[1],display:'block',position:'fixed'});
	    $('#change_dates_div').css('display','block');	// for search result page hidden form
	    $('#Header_').css('z-index','1');		
	    $('#Header').css('z-index','1');	
	    $('.header_properties').css('z-index','1');		// for header
	    $('#header_container').css('display','none');
	    $('.headerLines').css('display','none');
	}
}
function changeMenuColorOnHoverON(name){
	document.getElementById(name+'_menu_1').style.display='none';
	document.getElementById(name+'_menu_2').style.display='block';
}
function changeMenuColorOnHoverOFF(name){
	document.getElementById(name+'_menu_1').style.display='block';
	document.getElementById(name+'_menu_2').style.display='none';
}
function trim(str,chars){return ltrim(rtrim(str,chars),chars);}
function ltrim(str,chars){
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
function rtrim(str,chars){
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
function sendFeedBack(id,page_url,feedback_msg,sessid){
	var feedback_msg_value=$('#'+feedback_msg).val();
	var page_url_value=$('#'+page_url).val();
	feedback_msg_value = trim(feedback_msg_value);
	if(feedback_msg_value=='' || feedback_msg_value.substring(0,26)=='Please give your feedback.'){
		logChange(sessid,'feedback_empty_error');
		alert('Please enter the feedback message');
		return false;
	}
	feedback_msg_value=feedback_msg_value.replace(/\n/g, "<br/>");
	$.ajax({
		url: "/index.php?mode=feedback&page_url="+page_url_value+"&feedback_msg="+feedback_msg_value,
		async: false,
		type: "POST",
		success: function(html){
			$('#'+id).html('<div align="center"><br/><br/><br/><font color="white">Thank you for taking the time to share your feedback.</font></div>');
			$('#'+id).slideUp(3000);
			logChange(sessid,'feedback_success');
		}
	});
	return true;
}
function menuHoverON(id,st,active){$('#'+id).removeClass(st); $('#'+id).addClass(active); }
function menuHoverOFF(id,st,active){$('#'+id).removeClass(active); $('#'+id).addClass(st); }
//required to hide select dropdown on IE6
function toggleSelects(action){
var selects = document.getElementsByTagName('select');
	if(action == 'hide'){
		for(i=0; i < selects.length; i++) {	selects[i].style.visibility='hidden'; }
	} else if(action == 'show'){
		for(i=0; i < selects.length; i++) {	selects[i].style.visibility='';	}
	}
}
// use the maphoteltrack feature to register the tag properly and then redirect
function logClick(link,tag){ $.ajax({ url:"/MapHotelTrack/"+tag, success: function(html){ window.location.href=link; }}); return false; }

//v1.7
// Flash Player Version Detection
// Detect Client Browser type
// Copyright 2005-2008 Adobe Systems Incorporated.  All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
function ControlVersion()
{
	var version;
	var axo;
	var e;
	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry
	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}
	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");

			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful.

			// default to the first public version
			version = "WIN 6,0,21,0";
			// throws if AllowScripAccess does not exist (introduced in 6.0r47)
			axo.AllowScriptAccess = "always";
			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}
	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}
	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}
	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}

	return version;
}
// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;

	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}
	return flashVer;
}
// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];
        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}
function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?');
  else
    return src + ext;
}
function AC_Generateobj(objAttrs, params, embedAttrs)
{
  var str = '';
  if (isIE && isWin && !isOpera)
  {
    str += '<object ';
    for (var i in objAttrs)
    {
      str += i + '="' + objAttrs[i] + '" ';
    }
    str += '>';
    for (var i in params)
    {
      str += '<param name="' + i + '" value="' + params[i] + '" /> ';
    }
    str += '</object>';
  }
  else
  {
    str += '<embed ';
    for (var i in embedAttrs)
    {
      str += i + '="' + embedAttrs[i] + '" ';
    }
    str += '> </embed>';
  }
  document.write(str);
}
function AC_FL_RunContent(){
  var ret =
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}
function AC_SW_RunContent(){
  var ret =
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}
function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();
    switch (currArg){
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblclick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
      case "id":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace":
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}

// Globals
// Major version of Flash required
var requiredMajorVersion = 7;
// Minor version of Flash required
var requiredMinorVersion = 0;
// Revision of Flash required
var requiredRevision = 79;



/*
 * Lazy Load - jQuery plugin for lazy loading images
 *
 * Copyright (c) 2007-2011 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   http://www.appelsiini.net/projects/lazyload
 *
 * Version:  1.6.0
 *
 */
(function(a){a.fn.lazyload=function(b){var c={threshold:0,failure_limit:0,event:"scroll",effect:"show",container:window,skip_invisible:!0};b&&(null!==b.failurelimit&&(b.failure_limit=b.failurelimit,delete b.failurelimit),a.extend(c,b));var d=this;return 0==c.event.indexOf("scroll")&&a(c.container).bind(c.event,function(b){var e=0;d.each(function(){if(c.skip_invisible&&!a(this).is(":visible"))return;if(!a.abovethetop(this,c)&&!a.leftofbegin(this,c))if(!a.belowthefold(this,c)&&!a.rightoffold(this,c))a(this).trigger("appear");else if(++e>c.failure_limit)return!1});var f=a.grep(d,function(a){return!a.loaded});d=a(f)}),this.each(function(){var b=this;b.loaded=!1,a(b).one("appear",function(){this.loaded||a("<img />").bind("load",function(){a(b).hide().attr("src",a(b).data("original"))[c.effect](c.effectspeed),b.loaded=!0}).attr("src",a(b).data("original"))}),0!=c.event.indexOf("scroll")&&a(b).bind(c.event,function(c){b.loaded||a(b).trigger("appear")})}),a(c.container).trigger(c.event),this},a.belowthefold=function(b,c){if(c.container===undefined||c.container===window)var d=a(window).height()+a(window).scrollTop();else var d=a(c.container).offset().top+a(c.container).height();return d<=a(b).offset().top-c.threshold},a.rightoffold=function(b,c){if(c.container===undefined||c.container===window)var d=a(window).width()+a(window).scrollLeft();else var d=a(c.container).offset().left+a(c.container).width();return d<=a(b).offset().left-c.threshold},a.abovethetop=function(b,c){if(c.container===undefined||c.container===window)var d=a(window).scrollTop();else var d=a(c.container).offset().top;return d>=a(b).offset().top+c.threshold+a(b).height()},a.leftofbegin=function(b,c){if(c.container===undefined||c.container===window)var d=a(window).scrollLeft();else var d=a(c.container).offset().left;return d>=a(b).offset().left+c.threshold+a(b).width()},a.extend(a.expr[":"],{"below-the-fold":function(b){return a.belowthefold(b,{threshold:0,container:window})},"above-the-fold":function(b){return!a.belowthefold(b,{threshold:0,container:window})},"right-of-fold":function(b){return a.rightoffold(b,{threshold:0,container:window})},"left-of-fold":function(b){return!a.rightoffold(b,{threshold:0,container:window})}})})(jQuery)

