/**
 * RegionImageGallery
 * Object can be used as static class to implement functionality for image gallery
 * in hotel info box / region description tab.
 *
 * Should be included in head-section of document via script-tag.
 * Don't use dynamically. For some reason this didn't work in tests.
 *
 * Example:
 * <script src="/kunden_parameter/thomascook_nl/hib_content/js/regionImageGallery.js" type="text/javascript"></script>
 *
 * Then call init-method of object after generating the appropriate html-elements.
 *
 * Example:
 * RegionImageGallery.init(2, '_0');
 * 
 * @copyright 2010 Traveltainment
 * @version 1.1.0
 * 
 * modified 15.10.2010, if RegionImageGallery.firstImage is undefined re-init RegionImageGallery.
 *
 */
var RegionImageGallery = {
    idContent: 0,               // Default: 0; must be initialized prior to usage.
    idContentPf: "_0",
    regionMarkedElements : [],
    firstImage: null,

    /**
     * Call to initialize picture gallery
     *
     * @param idContent - Specifies the ID of the content block to work on
     * @param idContentPf - Prefix of content block element (usually "_0")
     */
    init : function (idContent, idContentPf) {
        RegionImageGallery.idContent = idContent;
        RegionImageGallery.idContentPf = idContentPf;
        RegionImageGallery.RegionTemplateInitScrollArea();
        
        // define click events for previous / next buttons
        jQuery("#regionContentSlideShowPrevBtn_" + RegionImageGallery.idContent).click(RegionImageGallery.RegionTemplateScrollToLeft);
        jQuery("#regionContentSlideShowNextBtn_" + RegionImageGallery.idContent).click(RegionImageGallery.RegionTemplateScrollToRight);

        RegionImageGallery.firstImage = jQuery('#idDiashowExists_' + RegionImageGallery.idContent + RegionImageGallery.idContentPf + ' img[cnt=0]')[0];
        if (typeof RegionImageGallery.regionMarkedElements == 'array') {
            if (RegionImageGallery.regionMarkedElements.length > 0) {
                RegionImageGallery.regionMarkedElements = null;
                delete RegionImageGallery.regionMarkedElements;
            }
        }
        RegionImageGallery.regionMarkedElements = [];
        
        //if (typeof console != 'undefined') { console.log(RegionImageGallery.firstImage); }
          
        if (RegionImageGallery.firstImage !== undefined) {
            RegionImageGallery.regionMarkFirstElement(RegionImageGallery.firstImage);
        } else {
            window.setTimeout(function () {
               RegionImageGallery.init(idContent, idContentPf);
            }, 300);
        }      
        
    },

    /**
     * Define scrolling to the right
     */
    RegionTemplateScrollToRight : function () {
        //if (typeof console != 'undefined') { console.log('RegionTemplateScrollToRight'); }
        
        var numThumbs, firstvisible, offset, clickedNo;
        numThumbs    = jQuery("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent).attr('countthumbs');
        firstvisible = jQuery("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent).attr('firstvisible');
        clickedNo    = jQuery("img[current='current']").attr("cnt");
        firstvisible = firstvisible * 1;
        clickedNo    = clickedNo * 1;
        
        // next image counter
        var nextVisible = firstvisible + 1;
        var nextCounter = clickedNo + 1;
        
        if (nextVisible <= numThumbs) {
            jQuery("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent + " img[current='current']").attr("current", "no");
            jQuery("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent + " img[cnt=" + nextCounter + "]")
                .attr("current", "current")
                .click();
            jQuery ("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent)
                .attr('firstvisible', nextVisible);
        }

        var scrollStartPosition = 2;
        var scrollEndPosition = 1;

        // do scroll if more than three images are available
        if (numThumbs > 3) {
            if ((nextCounter > scrollStartPosition) && (nextCounter < (numThumbs - scrollEndPosition))) {
                offset = (nextCounter * -120) + (scrollStartPosition * 115);
                jQuery ("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent)
                    .animate({"left" : offset + "px"}, 500);
            }
            
            // if last image, scroll to right to fit the last image
            if (nextVisible == numThumbs) {
                var sliderPosition = jQuery("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent).position();
                var lastOffset = parseInt(sliderPosition.left) - 22;
                jQuery ("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent)
                    .css({"left" : lastOffset + "px"});
            }
        }
    },

    /**
     * Define scrolling to the left
     */
    RegionTemplateScrollToLeft : function () {
        //if (typeof console != 'undefined') { console.log('RegionTemplateScrollToLeft'); }
        
        var numThumbs, firstvisible, offset, clickedNo;
        numThumbs    = jQuery("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent).attr('countthumbs');
        firstvisible = jQuery("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent).attr('firstvisible');
        clickedNo    = jQuery("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent + " img[current='current']").attr("cnt");
        firstvisible = firstvisible * 1;
        clickedNo    = clickedNo * 1;

        // next image counter
        var prevVisible = firstvisible - 1;
        var prevCounter = clickedNo - 1;

        if (prevVisible >= 1) {
            jQuery("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent + " img[current='current']").attr("current", "no");
            jQuery("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent + " img[cnt=" + prevCounter + "]")
                .attr("current", "current");
            
            jQuery ("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent)
                .attr('firstvisible', prevVisible);
            
            RegionImageGallery.regionMarkThumb(jQuery("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent + " img[current='current']")[0]);
        }
        
        var scrollStartPosition = 2;
        var scrollEndPosition = 1;
        
        if (numThumbs > 3) {
            if ((prevVisible > scrollStartPosition) && (prevVisible < numThumbs - scrollEndPosition)) {
                    
                var sliderPosition = jQuery("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent).position();
                offset = parseInt(sliderPosition.left) + 120;
                jQuery ("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent)
                    .animate({"left" : offset + "px"}, 500);
            } 
            
            // if first image, scroll to left to fit the first image
            if (prevCounter == 0) {
                jQuery ("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent)
                    .animate({"left" : "0px"}, 500);
            }
        }
                
    },
    
    /**
     * Define scrolling in case of clicking on a thumbnail
     */
    RegionTemplateScroll : function (imgObj) {
        
        var numThumbs              = jQuery("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent).attr('countthumbs');
        var previousCurrentCounter = jQuery("img[current='current']").attr("cnt") * 1;
        var newCurrentCounter      = jQuery(imgObj).attr("cnt") * 1;
        
        // unset previous current image
        jQuery("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent + " img[cnt=" + previousCurrentCounter + "]")
                .attr("current", "no");
        
        // set next current image
        jQuery ("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent)
            .attr('firstvisible', newCurrentCounter + 1);
        jQuery("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent + " img[cnt=" + (newCurrentCounter) + "]")
            .attr("current", "current");
       
        var scrollStartPosition = 2;
        var scrollEndPosition = 1;
       
        if (newCurrentCounter > previousCurrentCounter) {
            
            // do scroll if more than three images are available
            if (numThumbs > 3) {
                if ((newCurrentCounter > scrollStartPosition) && (newCurrentCounter < (numThumbs - scrollEndPosition))) {
                    offset = (newCurrentCounter * -120) + (scrollStartPosition * 115);
                    jQuery ("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent)
                        .animate({"left" : offset + "px"}, 500);
                }
                
                // if last image, scroll to right to fit the last image
                if ((newCurrentCounter + 1) == numThumbs) {
                    var sliderPosition = jQuery("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent).position();
                    var lastOffset = parseInt(sliderPosition.left) - 22;
                    jQuery ("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent)
                        .css({"left" : lastOffset + "px"});
                }
            }
            
        } else if (newCurrentCounter < previousCurrentCounter){
            
            if (numThumbs > 3) {
                if ((newCurrentCounter + 1 > scrollStartPosition) && (newCurrentCounter + 1 < numThumbs - scrollEndPosition)) {
                        
                    var sliderPosition = jQuery("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent).position();
                    offset = parseInt(sliderPosition.left) + 120;
                    jQuery ("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent)
                        .animate({"left" : offset + "px"}, 500);
                } 
                
                // if first image, scroll to left to fit the first image
                if (newCurrentCounter == 0) {
                    jQuery ("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent)
                        .animate({"left" : "0px"}, 500);
                }
            }
        }
    },

    /**
     * Define onmouseover/onmouseout events for gallery buttons
     * Works with one background-image (sprite)
     * @param obj button to work on
     * @param eventStr What to do
     *                 hover: Sets hover state of button
     *                 out:   Sets normal state of button
     */
    RegionTemplateButtonHover : function (obj, eventStr) {
        
        var imgSrc, btnUsage, xpos;

        imgSrc   = jQuery(obj).css("background-image");
        btnUsage = jQuery(obj).attr("btnUsage");
        if (imgSrc.search(/spacer\.gif/) == -1) {
            xpos  = 0;
            xpos += (btnUsage != "prev") ? 40 : 0;          // Left arrow regular: 0, right arrow regular: -40px
            xpos += (eventStr == "hover") ? 20 : 0;         // Left arrow hover: -20px, right arrow regular: -60px

            jQuery(obj).css({"background-position": "-" + xpos + "px 0"});
        }
    },

    /**
     * Set initial state of scrollarea, buttons, etc.
     */
    RegionTemplateInitScrollArea : function () {
        //if (typeof console != 'undefined') { console.log('RegionTemplateInitScrollArea'); }
         
        var numThumbs;   
        numThumbs = jQuery("#regionContentSlideShowTumbScrollArea_" + RegionImageGallery.idContent)
            .attr('countthumbs');

        jQuery("#regionContentSlideShowPrevBtn_" + RegionImageGallery.idContent + " img, #regionContentSlideShowNextBtn_" + RegionImageGallery.idContent + " img")
            .hover(
                function(){
                    RegionImageGallery.RegionTemplateButtonHover(this,"hover");
                },
                function(){
                    RegionImageGallery.RegionTemplateButtonHover(this, "out");
                }
            );
    },

    /**
     * Change class on hovered elements (the element underneath the cursor)
     * => Used for mouseover-event
     *
     * @param elem HTML-Element to be changed (usually an image)
     */
    regionHighlightThumb : function (elem) {
        if (elem) {
            elem.className = 'regionThumbSingleOver';
        }
    },

    /**
     * Change class on 'un'-hovered elements (the element underneath the cursor)
     * => Used for mouseout-event
     *
     * @param elem HTML-Element to be changed (usually an image)
     */
    regionResetThumb : function (elem) {
        if (elem && RegionImageGallery.regionMarkedElements[RegionImageGallery.idContent] && elem != RegionImageGallery.regionMarkedElements[RegionImageGallery.idContent][RegionImageGallery.idContentPf])
            elem.className = 'regionThumbSingle';
    },

    /**
     * Highlight an element (change it's class) and delete highlights on all
     * other similar elements. This also loads the selected image (elem) into the
     * 'idRegPicLarge'-element and recalculates the layout.
     * => Used for onclick-event
     *
     * @param elem HTML-Element to be changed (usually an image)
     */
    regionMarkThumb : function (elem) {
        //if (typeof console != 'undefined') { console.log('regionMarkThumb'); }
        
        if (RegionImageGallery.regionMarkedElements[RegionImageGallery.idContent]) {
            
            var oldElement = RegionImageGallery.regionMarkedElements[RegionImageGallery.idContent][RegionImageGallery.idContentPf];
            RegionImageGallery.regionHighlightThumb(elem);
            RegionImageGallery.regionMarkedElements[RegionImageGallery.idContent][RegionImageGallery.idContentPf] = elem;
            RegionImageGallery.regionResetThumb(oldElement);

            jQuery("#idRegPicLarge_" + RegionImageGallery.idContent + RegionImageGallery.idContentPf).attr("src", elem.getAttribute('origSrc'));
            jQuery("#regionIdSubline_" + RegionImageGallery.idContent + " #idDiaSubline_" + RegionImageGallery.idContent + "_0").html(elem.alt);

            window.setTimeout(RegionImageGallery.regionUpdatePicLargeShadow, 200);
        }
    },

    /**
     * Used in setup routine to initialize the first thumbnail
     *
     * @param elem HTML-Element to be changed (usually an image)
     */
    regionMarkFirstElement : function (elem) {
        
        //if (typeof console != 'undefined') { console.log('regionMarkFirstElement'); }
        //if (typeof console != 'undefined') { console.log(elem && (!RegionImageGallery.regionMarkedElements[RegionImageGallery.idContent] || RegionImageGallery.regionMarkedElements[RegionImageGallery.idContent][RegionImageGallery.idContentPf].getAttribute('cnt') > elem.getAttribute('cnt'))); }
        
        if (elem && (!RegionImageGallery.regionMarkedElements[RegionImageGallery.idContent] || RegionImageGallery.regionMarkedElements[RegionImageGallery.idContent][RegionImageGallery.idContentPf].getAttribute('cnt') > elem.getAttribute('cnt'))) {
            if (!RegionImageGallery.regionMarkedElements[RegionImageGallery.idContent]) {
                RegionImageGallery.regionMarkedElements[RegionImageGallery.idContent] = [];
            }
           
            RegionImageGallery.regionMarkThumb(elem);
        }
    },

    /**
     * Recalculation and refresh of large gallery image shadow(s)
     */
    regionUpdatePicLargeShadow : function () {
        var width, height;
        //if (typeof console != 'undefined') { console.log('regionUpdatePicLargeShadow'); }
        jQuery("#idDiashowExists_" + RegionImageGallery.idContent + RegionImageGallery.idContentPf + " .regionPicLarge").css("width", 1);
        
        width  = jQuery("img#idRegPicLarge_" + RegionImageGallery.idContent + RegionImageGallery.idContentPf).width();
        height = jQuery("img#idRegPicLarge_" + RegionImageGallery.idContent + RegionImageGallery.idContentPf).height();
        
        //if (typeof console != 'undefined') { console.log(width); }
//        jQuery("img#idRegPicLargeSchattenTop_" + RegionImageGallery.idContent + RegionImageGallery.idContentPf + ", img#idRegPicLargeSchattenBottom_" + RegionImageGallery.idContent + RegionImageGallery.idContentPf).css({
//           "width" : width + "px",
//           "height": "9px"
//        });
//
//        jQuery("img#idRegPicLargeSchattenLeft_" + RegionImageGallery.idContent + RegionImageGallery.idContentPf + ", img#idRegPicLargeSchattenRight_" + RegionImageGallery.idContent + RegionImageGallery.idContentPf).css({
//           "width": "9px",
//           "height" : height + "px"
//        });
//
//        width  = width * 1 + 18;


        // fallback if image width is not available at this moment.
        if (width == 0) {
           width = 300; 
        }

        jQuery("#idDiashowExists_" + RegionImageGallery.idContent + RegionImageGallery.idContentPf + " .regionPicLarge").css("width", width);
    }
    
};


