﻿var Prices = function($){
    var priv = {
        progressTimer : 200,
        $priceSelectedLink : null,
        acc : null,
        toolTipTimeoutID : null,
        currentDuration : "medium",	    
        lowestPriceMonth : '',
        triedLong : false,
        triedShort : false,
        
        initExtraScroll : function(){
            // set scrollbar
            $('#extra-scroll div').width($('table.pricegrid').width());
            $('div.leftpane').css('margin-top','26px');
            $('div.rightpane').css('margin-top','0');
//            $('#extra-scroll').bind("scroll", function () { 
//                $("div.rightpane").get(0).scrollLeft = this.scrollLeft; 
//            });
//            $('div.rightpane').bind("scroll", function () { 
//                $("#extra-scroll").get(0).scrollLeft = this.scrollLeft; 
//            });
            
            $('#extra-scroll').bind("mouseenter", function(){
                $('#extra-scroll').bind("scroll", function () { 
                    $("div.rightpane").get(0).scrollLeft = this.scrollLeft; 
                });
            });
            $('#extra-scroll').bind("mouseleave", function(){
                $('#extra-scroll').unbind("scroll");
            });
            $('div.rightpane').bind("mouseenter", function(){
                $('div.rightpane').bind("scroll", function () {
                    $("#extra-scroll").get(0).scrollLeft = this.scrollLeft; 
                });
            });
            $('div.rightpane').bind("mouseleave", function(){
                $('div.rightpane').unbind("scroll");
            });
        },
        
        positionInScreen : function($element, x, y, offsetX, offsetY)
        {   
            //make sure the element is part of the body to allow better absolute postitioning
            if($element.parent().get(0).tagName.toLowerCase() != "body"){
                $("body").append($element);
            }
            
            if(!$element || !x || !y)
                return;
            
            var elementWidth = $element.width();
            var elementHeight = $element.height();
            var clientHeight  = (document.documentElement.clientHeight ? document.documentElement.clientHeight : window.clientHeight);
            var clientWidth   = (document.documentElement.clientWidth  ? document.documentElement.clientWidth : window.clientWidth);
            var top           = $("HTML")[0].scrollTop;
            var bottom        = top + clientHeight;    
            
            var distanceToTop    = y - top;
            var distanceToBottom = bottom - y;
            var distanceToLeft   = x;
            var distanceToRight  = clientWidth - x;
            
            var finalX = x + offsetX;
            var finalY = y + offsetY;
            
            if((finalX + elementWidth + offsetX) > clientWidth){
                finalX = (x - 2*offsetX - elementWidth);
            }
            
            if((finalY + elementHeight + offsetY) > (clientHeight + top)){
                //stuck to bottom: finalY -= (finalY + elementHeight + offsetY) - (clientHeight + top);
                finalY = (y - offsetY - elementHeight);
            } 
            
            $element.css( {'top':(finalY)+'px', 'left':(finalX)+'px'} );
            $element.show();
        }
        
//        loadToolTip : function(pageX, pageY, accId, duration, roomType, date){
//            $('#price-tooltip').load(resources.path_prefix + '/utilpages/pricecalculation.aspx'+ 
//                '?acc='+accId+
//                '&dur='+duration+
//                '&rcode='+roomType+
//                '&date='+date+'&tooltip=true #calc-content table',
//                null, 
//                function(){
//                    if($('#price-tooltip').hasClass('hovered')){
//                        priv.positionInScreen($('#price-tooltip'), pageX, pageY, 25, 15);
//                    }
//                }
//            );
//        }
                
    };
    return {
    
        removeBasket : function () {
            $('#frmBasket').attr('src','about:blank');
            $('#frmBasket').height(1);
        },
        
        priceOver : function(pointer, evt){
            pointer = $(pointer);
            if (pointer.find("a").length == 0)
                return;
            var pageX = (evt.pageX ? evt.pageX : (evt.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - (document.documentElement.clientLeft || 0)));
            var pageY = (evt.pageY ? evt.pageY : (evt.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - (document.documentElement.clientTop || 0)));
            var tooltip  = $('#price-tooltip');
            var tooltipvalues = pointer.find("a").attr("rel").split('~');
            if(tooltipvalues[0] == '1'){
                tooltip.show();
                tooltip.find(".room-info").html(tooltipvalues[1]);
                tooltip.find(".tooltip-info").html(tooltipvalues[2]);
                if(tooltipvalues[3] == '1'){
                    tooltip.find(".tooltip-onrequest").show();
                } else {
                    tooltip.find(".tooltip-onrequest").hide();
                }
                if($(this).parent().hasClass('minocc')){
                    tooltip.find(".tooltip-minocc").show();
                } else {
                    tooltip.find(".tooltip-minocc").hide();
                }
                if($(this).parent().hasClass('maxocc')){
                    tooltip.find(".tooltip-maxocc").show();
                } else {
                    tooltip.find(".tooltip-maxocc").hide();
                }                
                tooltip.find(".price-info").html(tooltipvalues[4]);                
                priv.positionInScreen(tooltip, pageX, pageY, 25, 15);
            } else {
//                tooltipold.show();
//                tooltipold.find(".content").html("<div class='tooltip-info'>" + tooltipvalues[1] + "</div>");
//                if(tooltipvalues[2] == '1'){
//                    tooltip.find(".tooltip-onrequest").show();
//                } else {
//                    tooltip.find(".tooltip-onrequest").hide();
//                }
//                pointer.PositionInScreen(tooltipold, pageX, pageY, 25, 15);
            }
         },
    
        priceOut : function(){
            if(priv.toolTipTimeoutID != null){
                window.clearTimeout(priv.toolTipTimeoutID);
                priv.toolTipTimeoutID = null;
            }
            $('#price-tooltip').hide().removeClass('hovered');
        },
    
        showPriceTable : function () {

        
	        $('#priceTableMessage').hide();
            $('#priceloader').show();
            $('#monthFilter').bind('change', Prices.reloadPriceTab);
            $('#airPortFilter').bind('change', Prices.reloadPriceTab);
            
            //scroll to first available accommodation in pricetable (SW-589)	
            if ($('table.pricegrid tr.days td.available').length > 0)
            {
                $('.rightpane').get(0).scrollLeft = $('table.pricegrid tr.days td.available')[0].offsetLeft;            
                priv.initExtraScroll();            
                $("#extra-scroll").get(0).scrollLeft =  $('table.pricegrid tr.days td.available')[0].offsetLeft;
            }
            
            //(SW-907) if this tab does not contain prices, load another tab 
            if($('.noprices').css('display') == 'block' && priv.triedLong == false)
            {  
                Prices.filterPriceTab('long');
                priv.triedLong = true;
            }
            else if($('.noprices').css('display') == 'block' && priv.triedShort == false)
            {
                Prices.filterPriceTab('short');
                priv.triedShort = true;
            }
	    },
	    
	    showPriceCalculation : function () {
	        $('#price-calc-wait').hide();
            $('#price-calc').css("visibility", "visible").show();
	    },
	    
	    filterPriceTab : function(duration)
	    {
	        priv.currentDuration = duration;

	        Prices.reloadPriceTab();
	    },
	    
	    setLowestPriceMonth : function (month){
	        priv.lowestPriceMonth = month;
	    },
	    
	    reloadPriceTab : function (){
	        var timer = new Timer();
	        timer.Start();
	        $('#priceloader').hide();
            $('#priceTableMessage').show();
            var ran_number= Math.random();
            //$('#price-tooltip').remove();
            
            //if the #monthfilter is not defined (this happens only when the page is first loaded)
            //, try to get the selected month from the lister ($(".parent_lister_sel_month") is set in accomodation.aspx.cs)
            
            var sel_month = "-1"; //-1 is the default value, if sel_month is still -1 after the next statement, then the first available month is shown
            if(typeof(priv.lowestPriceMonth) != "undefined" && priv.lowestPriceMonth != null && priv.lowestPriceMonth != "")
            {
                if (priv.lowestPriceMonth.length == 5)
                {
                    sel_month = priv.lowestPriceMonth.substring(0,4) + "0" + priv.lowestPriceMonth.substring(4);
                }
                else
                {
                    sel_month = priv.lowestPriceMonth;
                }
                priv.lowestPriceMonth = ""; // set back to default value "". This value is set when clicking on the lowest price on acco page.
            }
            else if($('#monthFilter').length == 0 && $(".parent_lister_sel_month").text() != '')
            {
                sel_month = $(".parent_lister_sel_month").text();
            }
            else 
            {
                //if this is not the first load, get the value that is already selected
                sel_month = $('#monthFilter').val();
            }
            // get selected airport
            var sel_airport = "";
            if ($('#airPortFilter').length == 0 && $(".parent_lister_sel_airport").text() != '')
            {
                sel_airport = $(".parent_lister_sel_airport").text();
            }
            else if ($('#airPortFilter').length > 0 &&  ($('#airPortFilter').val() == '' ||  $('#airPortFilter').val() == 'undefined'))
            {
                sel_airport = $(".parent_lister_sel_airport").text();
            }
            else
            {
                sel_airport = $('#airPortFilter').val()
            }
            
            $("#priceloader").load(resources.path_prefix + '/utilpages/getcontrol.ashx'+ 
                '?acc='+$('#acc').attr('name')+
                '&loadControl='+encodeURI('~/controls/accommodation/pricetab.ascx')+
                '&selmonth='+sel_month+
                '&selairport='+sel_airport+
                '&duration='+priv.currentDuration +
                '&rand='+ran_number, 
                null,
                function(){ 
                    $('table.pricegrid tr.months td').each(
                        function(){ 
                            if($('span',this).length > 1){
                                $('span:first',this).css({paddingRight:'290px'});
                            }
                        }
                    );               
                    setTimeout('Prices.showPriceTable()', Math.max((priv.progressTimer - timer.Stop()), 0));
                }
            );
            
            $(".last_selected_month").html(sel_month);
	    },
	    
	    showCalculation : function(obj, airportcode){
            var $linkClick = $(obj);
            //if( !$linkClick.hasClass('selected') ){
            if(priv.$priceSelectedLink != null)
                priv.$priceSelectedLink.removeClass('selected');
            priv.$priceSelectedLink = $linkClick;
            $linkClick.addClass('selected');
            
            var $roomTypeRow = $linkClick.parent().parent();
            var duration = $roomTypeRow.prevAll('.dur').get(0).id.replace('d','');
            var roomType = encodeURI($roomTypeRow.attr('class').replace(' two-lines',''));
            var date = $($('tr.days td').get($linkClick.parent().get(0).cellIndex)).attr('id').replace('d','');
            var price = $linkClick.attr('name');
            
            var timer = new Timer();
            timer.Start();
            $('#price-calc-wait').show();
            $('#price-calc').hide();
            $('#frmBasket').css('width','0px');
            $('#frmBasket').css('height','0px');
            //$('#frmBasket').attr('src','');
            
            $("#price-calc .content").load(resources.path_prefix + '/utilpages/pricecalculation.aspx'+ 
                '?acc='+priv.acc+
                '&dur='+duration+
                '&rcode='+roomType+
                '&date='+date+' #calc-content', 
                null,
                function(){
                    if($('#packagId').length){
                        var packageid = $('#packagId').attr('name');
                        var departuredate = (date.substr(0,4)+'-'+date.substr(4,2)+'-'+date.substr(6,2));
                        var transportcode = 'VL';
                        var accommodationid = priv.acc;
                        
                        var extraHeight = 0;
                        if ($('#frmBasket').contents().find('#form1')[0] &&
							$('#frmBasket').contents().find('#form1')[0].action != null)
						{
							//if(window.frames[0].document.form1){
							var originalurl = $('#frmBasket').contents().find('#form1')[0].action;
                            var pid_originalurl = logic.getURLParamFromString('pid', originalurl);
                            var drt_originalurl = logic.getURLParamFromString('drt', originalurl);
                            var rtc_originalurl = logic.getURLParamFromString('rtc', originalurl);
                            var dep_originalurl = logic.getURLParamFromString('dep', originalurl);
                            var tpc_originalurl = logic.getURLParamFromString('tpc', originalurl);
                            var apc_originalurl = logic.getURLParamFromString('apc', originalurl);
                            var aid_originalurl = logic.getURLParamFromString('aid', originalurl);
                            var prc_originalurl = logic.getURLParamFromString('prc', originalurl);
                            
                            packageid = pid_originalurl + ";" + packageid;
                            duration = drt_originalurl + ";" + duration;
                            roomType = rtc_originalurl + ";" + roomType;
                            departuredate = dep_originalurl + ";" + departuredate
                            transportcode = tpc_originalurl + ";" + transportcode;
                            airportcode = apc_originalurl + ";" + airportcode;
                            price = prc_originalurl + ";" + price;
                            accommodationid = aid_originalurl + ";" + accommodationid;
                            
                            extraHeight = decodeURI(accommodationid).split(';').length*120;
                        }   
                        
                        var basketUrl = resources.path_prefix + "/reservation/basket.aspx?pid=" + packageid + "&drt=" + duration + "&rtc=" + roomType +
                                        "&dep=" + departuredate + "&tpc=" + transportcode + "&apc=" + airportcode + "&aid=" + accommodationid + "&prc=" + price;  
                        $('#frmBasket').attr('src', basketUrl);
                        $('#frmBasket').css('width','330px');
                        $('#frmBasket').css('height', (290+extraHeight)+'px');
                        setTimeout('Prices.showPriceCalculation()', Math.max((priv.progressTimer - timer.Stop()), 0));                                                        
                        
                        
                    } else {
                        // error
                    }
                }
            );
        },
        
        redraw : function(newHeight){
            $("#frmBasket").height(newHeight + 25);
            $('html').get(0).scrollTop += 1; //hack needed to position the basket correct
            $('html').get(0).scrollTop -= 1;
            
			//scroll the window if the element is not in the viewarea
			if($('html').get(0).scrollTop + $(window).height() < $("#frmBasket").offset().top + $("#frmBasket").height()){
			    $('html').get(0).scrollTop = $("#frmBasket").offset().top - $(window).height() + $("#frmBasket").height();
			}
        },
        
        OnReady : function(){
             $('#monthFilter').bind('change', Prices.reloadPriceTab);
             $('#airPortFilter').bind('change', Prices.reloadPriceTab);
             
             priv.initExtraScroll();
             
             priv.acc = $('#acc').attr('name');
             
             $(window).bind("load",
				function() {
                    Prices.reloadPriceTab();
				}
			);			
			
			$("#frmBasket").fixate({minTop:0, maxTop:$("#prices").height()});
        }
    }
}(jQuery);
