﻿var Accommodation = function(){
    var priv = {
        accoId : -1,
        addReviewClicked : false,
        // photo gallery values
        totalNrPhotos : 0,
        galleryPageCount : -1,
        totalPages : -1,
        currentPage : 1,
        currentPhotoIndex : -1,
        
        initFavoriteLogic : function() {		    
		    //test wether this is a favorite
		    var $favorite = $('#favorite');
		    if(personalItems.Contains("favorites", priv.accoId)){
		        $favorite.addClass("is-favorite");
		        $('span', $favorite).html('Bewaard');
		    }
		    
		    //bind the click event for the trigger
		    $favorite.bind("click",
		        function(evt){	
					//test for add or removal of the favo
					if($(this).hasClass("is-favorite")){
						$(this).removeClass("is-favorite");
						personalItems.Remove("favorites", priv.accoId);
					}
					else {
					    $(this).addClass("is-favorite");
						personalItems.Add("favorites", priv.accoId);
					}
					
					//prevent event bubbling
					return false;
				}
		    );
		},
		
		initPhotoGallery : function(){
		    var photoIndex = Logic.getURLParam('photoIndex');	
		    if(photoIndex != null && photoIndex != ""){
		        photoIndex = parseInt(photoIndex);
		    } else {
		        photoIndex = -1;
		    }  
		    $('#movephotos ul.gallery li img').each(function(i){
		        $(this).hover(
                    function () {
                        $(this).addClass('hover');
                    }, 
                    function () {
                        $(this).removeClass('hover');
                    }
                );
                if(photoIndex == i){
                    $(this).addClass('selected');
                }
            });
		
	        // set variabele
	        priv.totalNrPhotos = parseInt($('#totalPhotos').attr('name'));
	        priv.galleryPageCount = parseInt($('#galleryPageCount').attr('name'));
	        priv.totalPages = Math.ceil(priv.totalNrPhotos / priv.galleryPageCount);
	        if(photoIndex > -1 && photoIndex < priv.totalNrPhotos){
		        priv.currentPage = Math.ceil((parseInt(photoIndex)+1)/priv.galleryPageCount);
		    }
		    priv.currentPhotoIndex = photoIndex == -1 ? 0 : photoIndex;
		    $('#photo_index').text((priv.currentPhotoIndex+1));
		    
		    $('#total_photos').text(priv.totalNrPhotos);
		    
		    // set correct page
		    Accommodation.photoGalleryMove(priv.currentPage, true);
    		    
    		// only initialize paging when needed
		    var $pagers = $('#sidebar div.pagers');
    		if($pagers.length){    
		        // add photo gallery events
                $('#photo-next').bind('click', priv.photoGalleryNext);
                $('#photo-prev').bind('click', priv.photoGalleryPrevious);
                
                // build paging
                var paging = "";
                for(var i=1;i<=priv.totalPages;i++){
                    var selectedClass = '';
                    if(i == priv.currentPage) {
                        selectedClass = ' class="selected"';
                    }
                    paging += '<a href="javascript:Accommodation.photoGalleryMove('+i+');" id="page_'+i+'"'+selectedClass+'>'+i+'</a> ';
                }
                $('p', $pagers).append(paging);
            }
            
            var $photopagers = $('#content div.pagers');
            if($photopagers.length){ 
                // add photo gallery events
                $('#phototab-next').bind('click', priv.photoNext);
                $('#phototab-prev').bind('click', priv.photoPrevious);
                
                Accommodation.photoGalleryChange(priv.currentPhotoIndex);
            }
		},
		
		photoGalleryNext : function(){
		    var $nextButton = $('#photo-next');
		    if(!$nextButton.hasClass('disabled')){
		        Accommodation.photoGalleryMove(priv.currentPage + 1);
		    }
		},
		
		photoGalleryPrevious : function(){
		    var $previousButton = $('#photo-prev');
		    if(!$previousButton.hasClass('disabled')){
		        Accommodation.photoGalleryMove(priv.currentPage - 1);
		    }
		},
		
		photoNext : function(){
		    var $nextButton = $('#phototab-next');
		    if(!$nextButton.hasClass('disabled')){
		        Accommodation.photoGalleryChange(priv.currentPhotoIndex + 1);
		    }
		},
		
		photoPrevious : function(){
		    var $previousButton = $('#phototab-prev');
		    if(!$previousButton.hasClass('disabled')){
		        Accommodation.photoGalleryChange(priv.currentPhotoIndex - 1);
		    }
		},
		
		addReviewSuccess : function(){
		    priv.addReviewClicked = false;
		    $('#tbl-guestbook .error-message').html('');
		    $('#review-title').val('');
	        $('#review-email').val('');
	        $('#review-name').val('');
	        $('#review-text').val('');
		    $('#tbl-guestbook .success-message').show();
		},
		
		addReviewError : function(){
		    priv.addReviewClicked = false;
		    $('#tbl-guestbook .error-message').html('Er is een fout opgetreden. Probeer het later nog eens.');
		},
		
		addReview : function(){
		    if(!priv.addReviewClicked){
	            priv.addReviewClicked = true;
	            var $errorElement = $('#tbl-guestbook .error-message');
	            
	            var ajaxUrl = resources.path_prefix + '/utilpages/ajax-addreview.ashx';
	            var reviewtitle = $('#review-title').val();
	            var reviewemail = $('#review-email').val();
	            var reviewname = $('#review-name').val().stripTags();
	            var reviewtext = $('#review-text').val().stripTags();

	            if(reviewname == ''){
	                $errorElement.html('Gelieve een naam in te vullen.');
	                priv.addReviewClicked = false;
	            }
	            else if(reviewtext == ''){
	                $errorElement.html('Gelieve een bericht in te vullen.');
	                priv.addReviewClicked = false;
	            }
	            else if(reviewtitle == ''){
	                $errorElement.html('Gelieve een titel in te vullen.');
	                priv.addReviewClicked = false;
	            }
	            else if(reviewemail == ''){
	                $errorElement.html('Gelieve een correct emailadres in te vullen.');
	                priv.addReviewClicked = false;
	            } else {
	                var reg = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
                    if (!reg.test(reviewemail)) {
                        $errorElement.html('Gelieve een correct emailadres in te vullen.');
                        priv.addReviewClicked = false;
                    } else {
                        // if email is valid submit
	                    var dataStr = "reviewtitle=" + reviewtitle + "&reviewemail=" + reviewemail + "&reviewname=" + reviewname + "&reviewtext=" + reviewtext + "&accoid=" + priv.accoId;
    	                
	                    $.ajax({
			                type: "POST",
			                url: ajaxUrl,
				            data: dataStr,
				            async: true,
            				
			                success : priv.addReviewSuccess,
				            error : priv.addReviewError
			            });
                    }
	            }
	        }
		},
        
        bindEvents : function(){
            // add hovers for tabs
            $('#content .tabset li').hover(
                function () {
                    if(!$(this).hasClass('active')){
                        $(this).addClass('hover');
                    }
                }, 
                function () {
                    $(this).removeClass('hover');
                }
            );
            
            // add click event for review button
            $('#btn-review').bind('click', priv.addReview);
        },
        
         resizeTitle : function(){
            var $title = $("div.visual-right h2");
            var fontSize = parseInt($title.css("font-size"));
            while($title.height() > 35 && fontSize > 18){
                fontSize--;
                $title.css("font-size", fontSize + "px");
                $title.css("line-height", "22px");
            }
         }
    };
        
    return {
        
        OnReady	: function(){
            // set accommodationid
            priv.accoId = $('#accoId').attr('name');
            // add current accommodation to viewed items
            personalItems.Load("alreadyviewed");
            personalItems.Add("alreadyviewed", priv.accoId);
            
            // initialize favorite logic
            priv.initFavoriteLogic();
            			
			// check if page has subtabs
			var $subtabs = $('#content ul.sub-tabs');
			if($subtabs.length){
			    // change background color of active tab, because page has subtabs
			    $('#content .tabset li.active').css('background','#F9EDD4 url('+resources.path_prefix+'/images/master/bg-detailtab-hover.gif) repeat-x');
			
			    // set selected subtab
			    var selSubTab = Logic.getURLParam('subtab');
			    $("li > a", $subtabs).each(function (i) {
			        if( (i == 0 && selSubTab == "") || (selSubTab != "" && $(this).attr('href').indexOf('subtab='+selSubTab) != -1)){
			            $(this).addClass('active');
			        }
                });
			}
			
			// init photo gallery
            priv.initPhotoGallery();
            
            // load prices onready
            if(typeof(prices) != "undefined" && prices != null) {
			    prices.OnReady();
			}
			
			// bind page events
			priv.bindEvents();
			
			priv.resizeTitle();
			
			//set the carrent table classes
			$("table.carrent tr:odd").addClass("odd");
		},
		
		photoGalleryChange : function(newPhotoIndex){
		    priv.currentPhotoIndex = newPhotoIndex;
		    $('#photo_index').text((priv.currentPhotoIndex+1));
		    
		    // change photo source
		    //first show the loader by setting the background to a blank image
		    $('#showPhoto').attr('src',resources.path_prefix+'/images/pixel.gif');
		       
		    //now preload the new image
            var tmpImg = new Image();
            //now define the onload action
            tmpImg.onload = function(){
                $('#showPhoto').attr('src',tmpImg.src);
            };
            tmpImg.src = resources.path_prefix+'/utilpages/getimage.ashx?accoId='+priv.accoId+'&photoIndex='+newPhotoIndex;
		    
		    // highlight selected photo
		    $('#movephotos ul.gallery li img').each(function(i){
                if(newPhotoIndex == i){
                    if(!$(this).hasClass('selected')){
                        $(this).addClass('selected');
                    }
                } else {
                    $(this).removeClass('selected');
                }
            });
            
            // dis-/enable previous and next buttons
	        $btnPrevious = $('#phototab-prev');
	        $btnNext = $('#phototab-next');
	        if(priv.currentPhotoIndex > 0) {
	            $btnPrevious.removeClass('disabled');
	        } else if(!$btnPrevious.hasClass('disabled')){
	            $btnPrevious.addClass('disabled');
	        }
	        if(priv.currentPhotoIndex < (priv.totalNrPhotos-1)) {
	            $btnNext.removeClass('disabled');
	        } else if(!$btnNext.hasClass('disabled')){
	            $btnNext.addClass('disabled');
	        }
	        
	        // move page
	        var newCurrentPage = Math.ceil((parseInt(priv.currentPhotoIndex)+1)/priv.galleryPageCount);
	        Accommodation.photoGalleryMove(newCurrentPage);
		},
		
		photoGalleryMove : function(newPagePosition, noAnimation){
		    // only move when page is changed
		    if(priv.currentPage != newPagePosition || (noAnimation != null && noAnimation)){
		        // set selected page
		        $('#page_'+priv.currentPage).removeClass('selected');
		        $('#page_'+newPagePosition).addClass('selected');
		        priv.currentPage = newPagePosition;
    		    
    		    // dis-/enable previous and next buttons
		        $btnPrevious = $('#photo-prev');
		        $btnNext = $('#photo-next');
		        if(priv.currentPage > 1) {
		            $btnPrevious.removeClass('disabled');
		        } else if(!$btnPrevious.hasClass('disabled')){
		            $btnPrevious.addClass('disabled');
		        }
		        if(priv.currentPage < priv.totalPages) {
		            $btnNext.removeClass('disabled');
		        } else if(!$btnNext.hasClass('disabled')){
		            $btnNext.addClass('disabled');
		        }
    		    
    		    // slide the photos
		        var newLeft = (priv.currentPage - 1) * -280;
		        if(noAnimation != null && noAnimation){
		            $('#movephotos').css('left',newLeft+'px');
		        } else {
		            $('#movephotos').animate({ left: newLeft+'px' }, 500 );
		        }
		    }
		}
		
    }
}(jQuery);

