﻿/**
 * static object that handles page logic
 * @class 
 * @constructor
 * @param {jQuery} $ Reference to the jQuery object
 */
var AccoMain = function($){
    
    var config = {
		
        /**
         * maximum number of reviews to show initially
         * @private
         */
        maxReviews : 10,
        
        /**
         * maximum number of tips to show initially
         * @private
         */
        maxTips : 10,
        
        /**
         * jquery reference of the favorites button html object
         * @private
         */
        favoriteTrigger: "#favorite",
        compareTrigger: "#compare",
        compareMaximum : 5,
        
        galleryInitialized: false,

        galleryIndex: 0
    };
	
    /**
     * @namespace Private methods and variables
     */
    var priv = {
    
        /**
         * holds the name for the current sub-page (tab)
         * @private
         */
        currentTab : null,
        
        /**
         * holds the name for the current sub-sub-page (subtab)
         * @private
         */
        currentSubTab : null,
        
        /**
         * The Id of the current accommodation
         * @type Integer
         * @private
         */
        accoId : -1,
        
        /**
        * Generic way to open a new lightbox: the contents of the container identified by the supplied id
        * are loaded in a lightbox. Also, the lightbox is cached and thus only has to be initialized once.
        * @param {String} id The id of the container to show in the lightbox
        * @param {Object} options (Optional) Several options can be supplied to override default behavior of just
        * loading the contents of the container. When supplied, these options will be used to initialize the lightbox.
        * @private
        */
        openLightbox: function(id, options) {
            var lightbox = Lightbox.CreateCached(id, options);
            lightbox.Show();
        },
        
        /**
         * Void, fills the property currentTab with the correct value
         * @private
         */
        setCurrentTab : function(){
            priv.currentTab = $.query.get('view').toLowerCase();
            if (priv.currentTab.length < 1) {
                priv.currentTab = $('body').attr('class');
            }
            Log.Debug("AccoMain: currentTab is '" + priv.currentTab + "'");
         },
        
        /**
         * Void, fills the property currentTab with the correct value
         * @private
         */
        setCurrentSubTab : function(){
            priv.currentSubTab = $.query.get('sub').toLowerCase();
            if (priv.currentSubTab.length < 1) {
                priv.currentSubTab = $('body').attr('class');
            }
            Log.Debug("AccoMain: currentSubTab is '" + priv.currentSubTab + "'");
         },
         
        /**
         * Binds the events, sets the classes for the personal item logic
         * makes sure to update the alreadyviewed list, and adds logic to the favorites button
         * @private
         */
        personalItemsLogic :function() {
            //bind event to the page load, to update the "alreadyviewed" items
            $(window).bind("load",
                function() {
                    PersonalItems.Add("alreadyviewed", priv.accoId);
                    PersonalItems.ShowItemLinks();
                }
            );
             //other personal item logic is moved to Main:markFavoriteAndCompareItems
        },
                
        /**
         * Only show the first X items of a list; the rest is hidden and can be toggled by using a 'view more' link
         * @param {Integer} maxItemsCount The maximum number of items to show initially
         * @param {String} setName The class of the list
         * @param {String} (Optional) countSelector The css selector for selecting a place to show the count of remaining items
         * @private
         */
        hideItems: function (maxItemsCount, setName, countSelector) {
            Log.Info("AccoMain: Called priv." + setName + "Tab");
            
            //get the items html object
            var listSelector = 'ul.' + setName;
            var $items = $(listSelector + ' li');
            
            // hide all items that are more than the maximum
            if($items.length > maxItemsCount){
                for(var i = maxItemsCount; i < $items.length; i++){
                    $($items[i]).css("display", "none");
                }
                
                // set the total number of items
                if (typeof(countSelector) != "undefined" && countSelector) {
                    $(countSelector).html('(' + ($items.length - maxItemsCount) + ')');
                }
                
                // bind the show all items event to show all items link
                $('div.show-' + setName + ' a').bind("click", function(){
                    $items.show();
                    $('div.show-' + setName).hide();
                    //TODO correct the shades?
                });
                
                $('div.show-' + setName).show();
            }
            
            //finally show the ul
            $(listSelector).show();
        },
         
        /**
         *  Logic for reviews tab
         */
        reviewsTab : function(){
            priv.hideItems(config.maxReviews, "reviews", "#reviews-count");
        },
         
         /**
         *  Logic for tips tab
         */
        tipsTab : function(){
            priv.hideItems(config.maxTips, "tips", "#tip-count");
        },
        
        /**
        * Binds the events, sets the classes for gallery logic
        * @private
        */
        galleryLogic: function() {
            $('#main-image-link').bind('click', function(e) {
                priv.galleryIndex = 0;
                priv.showGallery();
            });
        },
        
        showGallery: function() {
            priv.openLightbox('pCarousel', {
                container: document.getElementById('pCarousel'),
                clone: false,
                onShowCallback: function() {
                    if (!priv.galleryInitialized) {
                        Carousel.init('#pCarousel ul', priv.galleryIndex, 5);
                        $('#main-photo').bind('click', function(e) {
                            Carousel.nextPhoto();
                        });
                        priv.galleryInitialized = true;
                    }
                    else {
                        Carousel.pagePhoto(priv.galleryIndex);
                    }
                },
                height: 615,
                width: 646
            });
        },
		
        syncHeight: function() {//resize visual block next to aside
		   if ($(".information-aside").length && $(".visual-block").length) { 
			   var th = $(".information-aside").height()-20;
			   $(".visual-block").height(th);
		   }
        },

        addObjectIndex: function() {
        	// look if there is an objectindex in the url
        	var objectIndex = $.query.get('objectIndex');
        	if (objectIndex === null || objectIndex === '') {
        		return;
        	}

        	// get the current url
        	var url = document.location.href;
        	var lastIndex = url.indexOf('?');
        	if (lastIndex == -1) {
        		lastIndex = url.length;
        	}
        	var startIndex = url.lastIndexOf('/');
        	url = url.substring(startIndex, lastIndex);

        	// look if there are links to the current url without the objectindex
        	var objectIndexSetterTimer = new Timer();
        	$("#main a").not("#prices-container a, #pPrintOptions a").each(function(i) {
        		if (this.href.indexOf(url) != -1) {
        			if (this.href.indexOf('objectIndex') == -1) {
        				var anchor = '';
        				var anchorIndex = this.href.indexOf('#');
        				if (anchorIndex != -1) {
        					anchor = this.href.substring(anchorIndex);
        					this.href = this.href.substring(0, anchorIndex);
        				}

        				if (this.href.indexOf('?') > -1) {
        					this.href = this.href + '&objectIndex=' + objectIndex + anchor;
        				} else {
        					this.href = this.href + '?objectIndex=' + objectIndex + anchor;
        				}
        			}
        		}
        	});

        	Log.Info("AccoMain: Adding objectIndices took : " + (objectIndexSetterTimer.Stop()) + " ms", -1);
        }
		
    };
    
    /** @scope AccoMain */
    return {

        /**
         * Initializes the logic for the current page
         * to be called on $(document).ready
         */
        OnReady: function(){
            Log.Info("AccoMain: Called OnReady");  
			
            //determine the current accoId
            priv.accoId = $("#accoId").val();
            
            //determine the current tab
            priv.setCurrentTab();
            
            //determine the current subtab, only for destinations and description main tabs
            if (priv.currentTab == "destination" || priv.currentTab == "descriptions") {
                priv.setCurrentSubTab();
            }

            // add objectindex to urls
            priv.addObjectIndex();
            
            //do favorite logic (bind events, set classes)
            priv.personalItemsLogic();
            
            //do gallery logic (bind events, set active thumbnail etc)
            priv.galleryLogic();

            //set area with image to the same height as area with details
            priv.syncHeight();

            // Moved criteo block from document.write() in the masterpagedetail.master file, to this place, we set it from the javascript instead.
            if (document.location.protocol != "https:")
				$("#criteoHolder").append('<div id="cto_se_7710507_ac" style="display:none"><div class="ctoWidgetServer">http://gogonl.widget.criteo.com/pgi/</div><div class="ctoDataType">sendEvent</div><div class="ctoParams">wi=7710507&amp;pt1=2&amp;i=' + priv.accoId + '</div></div>');
            
            //tab specific logic
            if(priv.currentTab == "reviews"){
                priv.reviewsTab();
            }
            else if(priv.currentTab == "destination")
            {
                if(priv.currentSubTab == "tips"){
                    priv.tipsTab();
                }
            }
            
            if (typeof(AccoPrices) != "undefined") {
			    var accoPricesTime = new Timer();
				AccoPrices.OnReady();
				Log.Info("AccoMain: AccoPrices Javascript load time was: " + (accoPricesTime.Stop()) + " ms", -1);
			}
        }
    };
}(jQuery);



