// Attach default event when document is ready
window.addEvent('domready', lmauinit);

function lmauinit()
{
	var docroot=lmaucontext + "/docroot/lastminute";
    // Initialise sIFR
//    if (typeof sIFR == "function"){
//    	sIFR.replaceElement(named({sSelector:"h1.title,h2.title",
//    	                           sFlashSrc:docroot+"/common/font/din-md.swf",
//    	                           sColor:"#ff34ab",
//    	                           sWmode:'transparent',
//    	                           sFlashVars:"textalign=left&offsetTop=2"}));
//    	sIFR.replaceElement(named({sSelector:".subhead",
//    	                           sFlashSrc:docroot+"/common/font/din-md.swf",
//    	                           sColor:"#444444",
//    	                           sWmode:'transparent',
//    	                           sFlashVars:"textalign=left&offsetTop=2"}));
//    	sIFR.replaceElement(named({sSelector:".feature h2",
//    	                           sFlashSrc:docroot+"/common/font/din-md.swf",
//    	                           sColor:"#ffffff",
//    	                           sWmode:'transparent',
//    	                           sFlashVars:"textalign=left&offsetTop=2"}));
//    	sIFR.replaceElement(named({sSelector:".search h1, .search h2, .searchwide h1, .container h1",
//    	                           sFlashSrc:docroot+"/common/font/din-md.swf",
//    	                           sColor:"#982e6c",
//    	                           sWmode:'transparent',
//    	                           sFlashVars:"textalign=left&offsetTop=2"}));
//    	sIFR.replaceElement(named({sSelector:".headline h1, .headline h2",
//    	                           sFlashSrc:docroot+"/common/font/din-md.swf",
//    	                           sColor:"#ff34ab",
//    	                           sWmode:'transparent',
//    	                           sFlashVars:"textalign=left&offsetTop=2"}));
//    	sIFR.replaceElement(named({sSelector:".panel h1, .panel h2, .hero h2, .login h2",
//    	                           sFlashSrc:docroot+"/common/font/din-md.swf",
//    	                           sColor:"#982e6c",
//    	                           sWmode:'transparent',
//    	                           sFlashVars:"textalign=left&offsetTop=2"}));
//    	sIFR.replaceElement(named({sSelector:".special h2",
//    	                           sFlashSrc:docroot+"/common/font/din-md.swf",
//    	                           sColor:"#444444",
//    	                           sWmode:'transparent',
//    	                           sFlashVars:"textalign=left&offsetTop=2"}));
//    }

    // Convert all 'a' links with 'external' class to new target window
    $ES('a.external').each(function(row) {
        row.target = '_blank';
    });
    
    // Convert all 'a' links with 'popup' class to launch new target window
    $ES('a.popup').each(function(row) {
        link = row.href;
        row.addEvent('click', function() {
            var popup = new Window.popup(link, {
                width:600,
                height:450,
                x:((Window.getWidth() - 600) / 2) + Window.getLeft(),
                y:((Window.getHeight() - 450) / 2) + Window.getTop()
            });
            return false;
        });
        row.href = null;
    });
    
    // Remove keywords from any search boxes with 'search' class
    $ES('input.search').each(function(row) {
        row.addEvent('focus', function ()
            {
                if (this.value == 'Enter keywords...') {
                    this.value = '';
                }
                this.focus = null;
            }.bindAsEventListener(row));
    });
    
    // Ensure textfilters are active for AJAX dropdowns
    $ES('form').each(function(frm) {
        frm.addEvent('submit', function (evt) {
            evt = new Event(evt);
            msg = '';
            $ES('.textfilter', frm).each(function (el) {
                var basename = el.id.replace(/_input$/, "");
                if ($(basename) && $(basename + '_input')) {
                    var cd = $(basename).getValue();
                    var tx = $(basename + '_input').getValue();
                    var hd = $(basename + '_hidden').getValue();          			     
                    if (!cd || (!tx || tx != hd)) {
                        msg = (el.title) ? el.title + "\n" : "Please fill out all required fields before submitting\n";
                        if ($(basename + '_error')) {
                            $(basename + '_error').setStyle('display', 'block')
                                                  .innerHTML = '<div class="error">' + msg + '</div>';
                            var myfx = new Fx.Style($(basename + '_error'), 'background-color').start('#fc0', '#fff');
                        }
                        el.focus();
                        evt.stop();
                    }
                    else {
                   		//get the checkin date
                   		var checkin = $('CHECKIN').getValue();   
                   		//checks to make sure the date has been inputted before proceeding
                   		if ((checkin!="dd/mm/yyyy")&&(checkin!="")) {
	                   		//get the country value
	                   		var coun = $('COUNTRY').getValue();
	                   		//number of milliseconds in 48 hours
	                   		var hour = 48;
	                   		var timeallowed = hour * 60 * 60 * 1000;
	                   		//get today's date.
		                    this.today = new Date();
 							this.today.setHours(0);
						    this.today.setMinutes(0);
						    this.today.setSeconds(0);
						    this.today.setMilliseconds(0);		                    
		          			//get the selected date details.
		          			var d = $('CHECKIN-dd').getValue();
		          			var m = $('CHECKIN-mm').getValue();
		          			var y = $('CHECKIN-yy').getValue();
		          			var selecteddate = new Date(y, m-1, d);
		          			//get the time difference between today's date and selected date in
		          			//milliseconds.
		          			var timediff = selecteddate.getTime() - this.today.getTime();
		                    if ((coun!="Australia")&&(coun!="New Zealand")&&(timediff<timeallowed)&&(timediff>=0)) {
		                        msg = "Please contact lastminute.com.au on 1300 132 799 to book international hotels within the next 2 days.\n";
		                        if ($(basename + '_error')) {
		                            $(basename + '_error').setStyle('display', 'block')
		                                                  .innerHTML = '<div class="error">' + msg + '</div>';
		                            var myfx = new Fx.Style($(basename + '_error'), 'background-color').start('#fc0', '#fff');
		                        }
		                        evt.stop();
	                        }
                        }
                    }
                }
            });
            if (datePickerController != 'undefined') {
                $ES('.datepickerbox', frm).each(function (el) {
                    datePickerController.fixDate(el);
                    if (!el.getValue() || (el.getValue().search(/^(\d{1,2}\/){2}\d{2,4}$/g) == -1 && el.getValue() != 'n/a')) {
                        msg = 'Please re-enter date in dd/mm/yyyy format.';
                        if ($(el.id + '_error')) {
                            $(el.id + '_error').setStyle('display', 'block')
                                               .innerHTML = '<div class="error">' + msg + '</div>';
                            var myfx = new Fx.Style($(el.id + '_error'), 'background-color').start('#fc0', '#fff');
                        }
                        evt.stop();
                    }
                });
                datePickerController.hideAll();
            }
        }.bindAsEventListener(frm));
    });
    
    // Remove default text for newsletter signup
    if ($('newsletter_signup')) {
        $('newsletter_signup').addEvent('focus', function ()
            {
                if (this.value == 'Enter your email address...') {
                    this.value = '';
                }
                this.focus = null;
            }.bindAsEventListener($('newsletter_signup')));
    }
}

Element.extend({
   wrap: function(el){
	el = $(el) || new Element(el);
	return el.injectBefore(this).adopt(this);
   }
});

// Show/hide hotel rows in table
function showHotel(classname)
{
    $A($ES('.' + classname)).each(function(row) {
        if (row.hasClass('hidden')) {
            row.removeClass('hidden');
            val = '';
        } else {
            val = (row.getStyle('display') == 'none') ? ((document.all) ? '' : 'table-row') : 'none';
        }
        row.style.display = val;
    });
    return false;
}

Window.extend({
	isLoaded: true,
	getHost:function(url){
		url = $set(url, window.location.href);
		var host = url;
		if(url.indexOf('http://') >= 0){
			url = url.substring(url.indexOf('http://')+7,url.length);
			if (url.indexOf(':')) {
			    url = url.substring(0, url.indexOf(":"));
			}
			if (url.indexOf('/')) {
				return url.substring(0,url.indexOf('/'));
		    }
			return url;
		}
		return false;
	},
	getQueryStringValue: function(key) {
		var qs = window.location.search; //get the query string
		if(qs == "") return null; //if there isn't one, return null
		if(qs.indexOf("?") == 0)qs = qs.substring(1, qs.length); //remove the question mark
		//return qs.parseQuery()[key];
		
		//CR 7691 - 20080407 - added by KT
        //the above qs.ParseQuery()[key] does not seem to work.
        var pairs = qs.split(/[;&]/);
        for (var i = 0; i < pairs.length; i++) {
            var keyval = pairs[i].split('=');
            if (!keyval || keyval.length != 2) continue;
            if (keyval[0] == key) {
                //var key = unescape(keyval[0]);
                var val = unescape(keyval[1]);
                val = val.replace(/\+/g, ' ');
                return val;
            }
        }
		
	},
	
	getPort: function(url) {
		url = $set(url, window.location.href);
		var re = new RegExp(':([0-9]{4})');
		var m = re.exec(url);
	  if (m == null) return false;
	  else {
			var port = false;
			m.each(function(val){
				if($type.isNumber(val)) port = val;
			});
	  }
		return port;
	},
		disableIEBgCache:function(disable){
		try {	
			document.execCommand('BackgroundImageCache', false, disable);
		} catch(e) {}
	},
	
	getLeft: function() {
	    return (window.screenX != undefined) ? window.screenX : window.screenLeft;
	},
	
	getTop: function() {
	    return (window.screenY != undefined) ? window.screenY : window.screenTop;
	}
});

function calculateDate(dt, el)
{
    var days = $(el).getValue();
    var picker = datePickerController.datePickers[dt];
    var dep = $(dt + '-departure');
    var dep_dd = $(dt + '-departure-dd');
    var dep_mm = $(dt + '-departure-mm');
    var dep_yy = $(dt + '-departure-yy');
    
    if (!days || !dep || !dep_dd || !dep_mm || !dep_yy) {
        return false;
    }
    
    if (typeof(picker.dateSet) !== 'object') {
        dep.innerHTML = '-';
        return false;
    }
    
    datePickerController.fixDate(dt);
    picker.setDateFromInput();

    if (!picker.dateSet || picker.dateSet == 'NaN') {
        dep.innerHTML = '(Invalid date)';
        return false;
    }
    
    var depdate = datePickerController.dateAdd(picker.dateSet, days);
    
    var dy = (depdate.getDate() < 10) ? '0' + depdate.getDate() : depdate.getDate();
    //var mt = (depdate.getMonth() < 10) ? '0' + (depdate.getMonth() + 1) : (depdate.getMonth() + 1);
    var mt = ((depdate.getMonth() + 1) < 10) ? '0' + (depdate.getMonth() + 1) : depdate.getMonth() + 1;
    var yr = depdate.getFullYear();
    
    dep_dd.value = dy;
    dep_mm.value = mt;
    dep_yy.value = yr;
    
    dep.innerHTML = ' ' + dy + '/' + mt + '/' + yr;

}

function copyDate(el, ds)
{
    el = $(el);
    ds = $(ds);
    
    datePickerController.fixDate(el);

    if (!el || !ds) {
        return false;
    }
    
    if (ds.value == 'dd/mm/yyyy') {
        ds.value = el.value;
        datePickerController.fixDate(ds);
    }
}

function toggleOn(el)
{
    $E('.datepickerbox', el).value = 'dd/mm/yyyy';
    if (pr = _checkToggleWrapper(el)) {
        var marginChange = new Fx.Style(pr, 'height', {duration:600,
                                                       transition:Fx.Transitions.bounceOut,
                                                       onComplete: function() {
                                                           pr.setStyle('overflow', 'visible')
                                                           pr.setStyle('height', 'auto');
                                                       }.bind(pr)});
        marginChange.start($(el).getCoordinates().height);
    }
}

function toggleOff(el)
{
    $E('.datepickerbox', el).value = 'n/a';
    if (pr = _checkToggleWrapper(el)) {
        pr.setStyle('overflow', 'hidden');
        var marginChange = new Fx.Style(pr, 'height', {duration:200});
        marginChange.start(0);
    }
}

function _checkToggleWrapper(el)
{
    if (!$(el)) {
        return false;
    }
    pr = $(el).getParent();
    if ($(el).getParent().getTag() != 'div') {
        $(el).wrap('div');
        pr = $(el).getParent();
    }
    return pr
}

Window.popup = new Class({
	setOptions: function(options) {
		this.options = Object.extend({
			width: 500,
			height: 300,
			x: 50,
			y: 50,
			toolbar: 0,
			location: 0,
			directories: 0,
			status: 0,
			scrollbars: 'auto',
			resizeable: 1,
			name: 'popup'
		}, options || {});
	},
	initialize: function(url, options){
		this.url = url || false;
		this.setOptions(options);
		if(this.url) this.openWin();
	},
	openWin: function(url){
		url = url || this.url;
		this.window = window.open(url,
			this.options.name,
			'toolbar='+this.options.toolbar+
			',location='+this.options.location+
			',directories='+this.options.directories+
			',status='+this.options.status+
			',scrollbars='+this.options.scrollbars+
			',resizable='+this.options.resizeable+
			',width='+this.options.width+
			',height='+this.options.height+
			',top='+this.options.y+
			',left='+this.options.x);
		this.focus();
		return this.window;
	},
	focus: function(){
		this.window.focus();
	},
	close: function(){
		this.window.close();
	}
});

var legacyPopup = Window.popup.extend({
	setOptions: function(){
		this.parent();
		this.options = Object.extend({
			width: 516, 
			height: 350
		}, this.options);
	}
});

var GetValue = Window.getQueryStringValue;

Tabs = new Class({
    initialize: function(el) {
        this.container = el;
        this.tabs = $A([]);
        this.panels = $A([]);
        Window.onDomReady(this.setup.bind(this))
    },
    
    setup: function() {
        $ES('.tabs li').each(function(tab) {
            el = tab.getElement('a')
                    .getProperty('href');
            el = el.substring(el.indexOf('#') + 1);
            if ($(el)) {
                $(el).setStyle('display', (tab.hasClass('selected')) ? 'block' : 'none');
                this.tabs.push(tab);
                this.panels.push($(el));
                tab.addEvent('click', this.select.pass([tab, el], this));
            }
        }, this);
        this.container = $(this.container);
    },
    
    select: function(tab, el) {
        this.tabs.each(function(item) {
            item.removeClass('selected');
        });
        this.panels.each(function(item) {
            item.setStyle('display', (item.getProperty('id') == el) ? 'block' : 'none');
        });
        tab.addClass('selected');
    }
});

MenuSelector = new Class({
    initialize: function(el, list) {
        var parent = $(el);
        var menu = $ES('li', parent);
        var els = [];
        
        for (var loop = 0; loop < list.length; loop++) {
            link = $E('a', menu[loop]);
            link.setStyle('cursor', 'pointer');
            link.addEvent('click', function (li, link, list)
            {
                menu.each(function(obj) {
                    obj.removeClass('selected');
                });

                $A(list).each(function(obj) {
                    $(obj).setStyle('display', 'none');
                });

                li.addClass('selected');
                $(link).setStyle('display', 'block');
                this.blur();
                return false;
            }.pass([menu[loop], list[loop], list], link));
        }
    }
});

//CR 7871 - This function has been created to allow users to bookmark the site
function createBookmark(title,url) {

	if (window.sidebar) { // Mozilla Firefox Bookmark
	    window.sidebar.addPanel(title, url,"");
	} else if( window.external ) { // IE Favorite
	    window.external.AddFavorite( url, title); }
	else if(window.opera && window.print) { // Opera Hotlist
	    return true;
	}

}


