
jQuery.namespace('svr.home.map', 'svr.home.reviews');

svr.home.map = {

    imgId:                  'featuredImg',
    titleId:                'featuredTitle',
    descriptionId:          'featuredDescription',

    locDataContainerId:     'locationData',
    popupId:                'map_link_popup',

    imgBase:                '/images/locations/',
    origImgSrc:             '',
    origTitle:              '',
    origDescription:        '',

    addMouseActions: function(link, addClickHandler){
        var self = this;
        $(link).hover(
            function(){
                self.onMouseOver(this);
            },
            function(){
                self.onMouseOut(this);
            }
        );

        if (addClickHandler) {
            $(link).click(function(e){
                self.onClick(this, e);
            });
        }
    },

    onMouseOver: function(link){
        var x = this.getImgSrcByLink(link);
        $('#' + this.imgId).attr('src', this.getImgSrcByLink(link));
        var data = this.getDataByLink(link);
        $('#' + this.titleId).html(data.title);
        $('#' + this.descriptionId).html(data.description);
        return true;
    },

    onMouseOut: function(link){
        $('#' + this.imgId).attr('src', this.origImgSrc);
        $('#' + this.titleId).html(this.origTitle);
        $('#' + this.descriptionId).html(this.origDescription);
        return true;
    },

    onClick: function(link, e){
        this.removeAntiPukePopup();
        this.createAntiPukePopup(link, e);
    },

    createAntiPukePopup: function (link, e){
        e.preventDefault();
        var href = link.href;
        var matches  = href.match(/.*id=(.*)/);
        var locId = matches[1];
        var data = this.getDataByLocationId(locId);
        var t = [], i = 0;
        t[i++] = '<div id="' + this.popupId + '" style="position:absolute; left:' + e.pageX + 'px; top:' + e.pageY + 'px;">';
        t[i++] = '<p class="title">' +  data.title + '</p>';
        t[i++] = '<p>Please select an offer type.</p>';
        t[i++] = '<p><a href="' + href + '&as_otype=rental_longterm">Long Term Rental  &raquo;</a></p>';
        t[i++] = '<p><a href="' + href + '&as_otype=rental_holiday">Holiday Rental &raquo;</a></p>';
        t[i++] = '<p class="close"><a href="#" onclick="svr.home.map.removeAntiPukePopup(); return false;">Close</a></p>';
        t[i++] = '</div>';
        $('body').append(t.join(''));
        return false;
    },

    removeAntiPukePopup: function(){
        $('#' + this.popupId).remove();
    },

    getLocationIdByLink: function(link){
        return link.id.substr(4);
    },

    getImgSrcByLink: function(link){
        var locId = this.getLocationIdByLink(link);
        return this.getImgSrcByLocationId(locId);
    },

    getImgSrcByLocationId: function(locId){
        return this.imgBase + locId + '.jpg';
    },

    getDataByLink: function(link){
        var locId = this.getLocationIdByLink(link);
        return this.getDataByLocationId(locId);
    },

    getDataByLocationId: function(locId){
        var data = {
            title:          $('#li_' + locId + ' .title').html(),
            description:    $('#li_' + locId + ' .description').html()
        };
        return data;
    },

    preloadImages: function(){
       var imageKeys = [
            'aophor',
            'bangtao',
            'bypass',
            'boatlagoon',
            'capepanwa',
            'chalong',
            'chengtalay',
            'dulwich',
            'kalim',
            'kamala',
            'karon',
            'kata',
            'kathu',
            'kohmaprao',
            'kohsirey',
            'laguna',
            'layan',
            'lochpalm',
            'maikhao',
            'naiharn',
            'naithon',
            'naiyang',
            'paklok',
            'patong',
            'phukettown',
            'rawai',
            'surin',
            'thalang',

            'pcc',
            'bluecanyon',
            'phukana',
            'lagunagc',
            'missionhills',
            'rpm',
            'yachthaven'
       ];

        for (var i = 0; i < imageKeys.length; i++) {
            var img = new Image(); 
            img.src = this.imgBase + imageKeys[i] + '.jpg';
        }
    },

    run: function(){
        
        // set the orig img, title, data
        this.origImgSrc = $('#' + this.imgId).attr('src');
        this.origTitle = $('#' + this.titleId).html();
        this.origDescription = $('#' + this.descriptionId).html();

        // preload the images
        this.preloadImages();

        var self = this;

        // add hover handlers to the map text-links
        $('.Location li a').each(function(){
           self.addMouseActions(this, true);
        });

        // add hover handlers to the map area-links
        $('#phuket_image_map area.linked').each(function(){
            self.addMouseActions(this, true);
        });

        // add hover to the non-linked areas
        $('#phuket_image_map area.unlinked').each(function(){
            self.addMouseActions(this, false);
        });
    }
};

svr.home.reviews = {

    run: function(){
        this.cycle();
        this.addClickHandlers();
    },

    cycle: function(){

        // cycle the reviews
        $('#reviews').cycle({
            fx:                 'scrollUp',
            speed:              3000,
            timeout:            5000,
            pause:              1,
            containerResize:    0,
            fit:                0,
            height:             '250px'
        });
    },

    addClickHandlers: function(){
        $('#reviews .review').each(function(){
            $(this).click(function(){
                window.location = $('a', this).first().attr('href');
            });
        });
    }
};

svr.home.cdlc  = {

    container: [],
    propertyIndexes:[],
    timers: [],
    containerIds: [],

    timeout: 6000,
    itemsPerContainer: 4,

    populateContainers: function(){
        var cdlc = this;
        $('.cdlc_properties').each(function(containerIndex){
            cdlc.container[containerIndex] = [];
            cdlc.propertyIndexes[containerIndex] = 0;
            cdlc.timers[containerIndex] = null;
            cdlc.containerIds[containerIndex] = this.id;
            $('li', this).each(function(propertyIndex){
                cdlc.container[containerIndex][propertyIndex] = '<li>' + $(this).html() + '</li>';
            });
            cdlc.addHoverPause(containerIndex);
        });
    },

    addTimeouts: function(){
        for (var containerIndex = 0; containerIndex < this.container.length; containerIndex++) {
            this.addTimeout(containerIndex);
        }
    },

    addTimeout: function(containerIndex){
        this.timers[containerIndex] = setTimeout(this.createTimeoutFunction(containerIndex), this.timeout);
    },

    clearTimeout: function(containerIndex){
        if (this.timers[containerIndex]){
            clearTimeout(this.timers[containerIndex]);
        }
    },

    createTimeoutFunction: function(containerIndex){
        var cdlc = this;
        var fn = function(){
            var buf = cdlc.getNextPropertyBuffer(containerIndex);
            cdlc.transition(containerIndex, buf);
            cdlc.clearTimeout(containerIndex);
            cdlc.addTimeout(containerIndex);

        }
        return fn;
    },

    getNextPropertyBuffer: function(containerIndex){
        var buf = '';
        for (var i = 0; i < this.itemsPerContainer; i++) {
            var propertyIndex = this.getNextPropertyIndex(containerIndex);
            buf += this.container[containerIndex][propertyIndex];
        }
        return buf;
    },

    getNextPropertyIndex: function(containerIndex){
        var currIndex = this.propertyIndexes[containerIndex];
        currIndex++;
        var nextIndex = (currIndex < this.container[containerIndex].length) ? currIndex : 0;
        this.propertyIndexes[containerIndex] = nextIndex;
        return nextIndex;
    },

    transition: function(containerIndex, buf){
        $('#' + this.containerIds[containerIndex]).fadeOut('slow', function(){
            $(this).html(buf).fadeIn('slow');
        });
    },

    addHoverPause: function(containerIndex){
        var cdlc = this;
        $('#' + this.containerIds[containerIndex]).hover(
            function(){
                cdlc.clearTimeout(containerIndex);
            },
            function(){
                cdlc.addTimeout(containerIndex);
                // perform an immediate transition
                // var fn = cdlc.createTimeoutFunction(containerIndex);
                // fn.call();
            }
        );
    },

    run: function(){
        this.populateContainers();
        this.addTimeouts();
    }
};

(function($) {

    $(document).ready(function(){

        // Map interactivity
        svr.home.map.run();

        // Review interactivity
        svr.home.reviews.run();

        // CDLC interactivity
        svr.home.cdlc.run();

    });
})(jQuery);



