
/* Travel Deals Widget V.1.0 */

var domain = "images.res99.com";
var proto = "http://";
var s = document.getElementsByTagName('script');

for (var x = 0; x < s.length; x++) {
    var src = s[x].src;
    if (src.match(/\/js\/deals\/widget\.js/)) {
        var urlparts = new Array();
        var urlparts = src.split("/");
        proto = urlparts[0] + '//';
        domain = urlparts[2];
    }
}

if (typeof jQuery == 'undefined') {
    include("/js/jquery.1.4.3-min.js", "js");
}

include("/js/ui/ui.core.js");
include("/js/ui/ui.tabs.js");
include("/js/ui/ui.accordion.js");

var TravelDealsWidget = function(){
    this.domain = domain;
    this.init();
};

TravelDealsWidget.prototype.init = function(){
    this.url = '/deals-service/?encoding=json';
    this.type = 'tabs';
    this.dealsMsg = 'saving';
    this.protocol = 'http://';
    this.websiteId = '10000999';
    this.origins = '{ "cities": [ { "id": "NYC", "state": "NY", "country": "US", "label": "New York, NY (US)" } ] }';
    this.destinations = '{ "cities": [ { "id": "LAS", "state": "NV", "country": "US", "label": "Las Vegas, NV (US)" } ] }';
    this.title = 'Top Travel Deals';
    this.campaign = 'Htl,Air,Pkg';
    this.msg = 'There are no deals for the destination you have selected. Please select a different destination or check back at a later date for new deals.';
    this.errorCallback = '';
}

TravelDealsWidget.prototype.renderTo = function(divId){

    var $this = this;
    var camps = this._decodeCampaign();
    
    var widget = $('<div>');
    widget.addClass('dealswidget'); // add main class
    widget.append($('<h2>').html(this.title)); // widget title
    $("#" + divId).html(''); // clear target element
    $("#" + divId).append(widget); // create container
    $("#" + divId).attr('style', 'width: 230px; text-align: left');
       
    var popups = this._propPopup();
    popups.appendTo(widget);

    var container = $('<div id="travel-widget-container">');
    container.appendTo(widget);
    
    var hotel = $('<div id="travel-deals-hotel">');
    var flight = $('<div id="travel-deals-flight">');
    var flighthotel = $('<div id="travel-deals-flighthotel">');
    var form = $('<form>');
    
    var has_hotels = false;
    var has_flight = false;
    var has_pkg = false;
    
    if (camps.hotel) {
        has_hotels = true;
        hotel.addClass('deals'); // add deals class
    }
    if (camps.air) {
        has_flight = true;
        flight.addClass('deals'); // add deals class
    }
    if (camps.pkg) {
        has_pkg = true;
        flighthotel.addClass('deals'); // add deals class
    }

    if (this.origins) {
        var dest = this._destinationCombo(divId, 'departures', 'origin', this.origins);
        dest.appendTo(form);
    }
    
    if (this.destinations) {
        var dep = this._destinationCombo(divId, 'destinations', 'destination', this.destinations);
        dep.appendTo(form);
    }
    
    if (this.type == 'tabs') {
        var tab_container = this._generateTabs(has_hotels, has_flight, has_pkg);
        tab_container.appendTo(container);
    }
    
    if (has_hotels) {
        if (this.type == 'accordion') {
            var head = this._generateAccordion('hotel', has_hotels, has_flight, has_pkg);
            head.appendTo(container);
        }
        hotel.appendTo(container);
    }
        
    if (has_flight) {
        if (this.type == 'accordion') {
            var head = this._generateAccordion('flight', has_hotels, has_flight, has_pkg);
            head.appendTo(container);
        }
        flight.appendTo(container);
    }
    
    if (has_pkg) {
        if (this.type == 'accordion') {
            var head = this._generateAccordion('pkg', has_hotels, has_flight, has_pkg);
            head.appendTo(container);
        }
        flighthotel.appendTo(container);
    }
    
    if (this.type == 'links') {
        var links_container = this._generateTabs(has_hotels, has_flight, has_pkg);
        links_container.appendTo(container);
    }
    
    if (this.type == 'tabs' || this.type == 'links') {
        container.tabs();
    }
    
    if (this.type == 'tabs') {
        container.addClass("tabs");
    }
    
    if (this.type == 'links') {
        container.addClass("links");
    }
    
    if (this.type == 'accordion') {
    
        hotel.css('height','180px');
        hotel.css('overflow','hidden');
        flight.css('height','180px');
        flight.css('overflow','hidden');
        flighthotel.css('height','180px');
        flighthotel.css('overflow','hidden');
                    
        container.accordion({
            changestart: function(event, ui){
                $("#travel-widget-container .deals .a").show();
                $("#travel-widget-container .deals .nolink").hide();
            },
            change: function(event, ui){
                $("#travel-widget-container .deals .a").show();
                $("#travel-widget-container .deals .nolink").hide();
            }
        });
        
        container.addClass("accordion");
    }
    
    form.appendTo(widget);
    
    $.getJSON(this.protocol + this.domain + this.url + "&callback=?", {
    
        src: this.websiteId,
        origin: this.origin,
        destination: this.destination,
        campaigns: this.campaign,
        extension: 'jsonp'
    
    }, function(data){
    
        if (data.error && data.error == 1) {
            if ($this.errorCallback) {
                $this.errorCallback(data.type, data.message);
            }
        }
        
        if (data.deals.origin) {
            $this._selectLocation('origin',data.deals.origin);
        }
        if (data.deals.destination) {
            $this._selectLocation('destination',data.deals.destination);
        }

        if (camps.hotel) {
            if (data.deals.hotels.length) {
                var hotel_results = $this._resultsContent(data.deals.hotels);
                hotel.html(hotel_results);
            }
            else {
                hotel.html('<div>' + $this.msg + '</div>');
            }
        }
        
        if (camps.air) {
            if (data.deals.air.length) {
                var air_results = $this._resultsContent(data.deals.air);
                flight.html(air_results);
            }
            else {
                flight.html('<div>' + $this.msg + '</div>');
            }
        }
        
        if (camps.pkg) {
            if (data.deals.packages.length) {
                var pkg_results = $this._resultsContent(data.deals.packages);
                flighthotel.html(pkg_results);
            }
            else {
                flighthotel.html('<div>' + $this.msg + '</div>');
            }
        }
        
        if (has_hotels && data.deals.hotels.length) {
            
            $("#travel-deals-hotel a").hover(function(){
            
                $(".dealswidget #dealprop").show();
                $(document).unbind('mousemove');
                $this._showProperties(this);
                $this._propFillPopup($(this).attr('name'), data.deals.hotels);
                
            }, function(){
                $(document).bind('mousemove', function(e){
                
                    var propleft = $(".dealswidget #dealprop").css("left");
                    propleft = propleft.split("px");
                    propleft = Number(propleft[0]);
                    
                    var proptop = $(".dealswidget #dealprop").css("top");
                    proptop = proptop.split("px");
                    proptop = Number(proptop[0]);
                    
                    if ((e.pageX < propleft ||
                    e.pageX > (propleft + $(".dealswidget #dealprop").outerWidth(true))) ||
                    (e.pageY < proptop ||
                    e.pageY > (proptop + $(".dealswidget #dealprop").outerHeight(true)))) {
                    
                        $(".dealswidget #dealprop").hide();
                        
                    }
                });
            });
        }
    });
    
};

TravelDealsWidget.prototype.unload = function(){
    $("#travel-deals-hotel a").unbind('mouseenter mouseleave');
}

TravelDealsWidget.prototype.refresh = function(target){

    var origin = $('#departures').val();
    var destination = $('#destinations').val();
    
    this.origin = origin;
    this.destination = destination;
    this.unload();
    this.renderTo(target);
    
}

TravelDealsWidget.prototype._decodeCampaign = function(){

    var array = this.campaign.split(',');
    var hash = {
        'hotel': 0,
        'air': 0,
        'pkg': 0
    };
    
    for (var i = 0; i < array.length; i++) {
        if (array[i] == 'Htl') {
            hash.hotel = 1
        }
        if (array[i] == 'Air') {
            hash.air = 1
        }
        if (array[i] == 'Pkg') {
            hash.pkg = 1
        }
    }
    
    return hash;
}

TravelDealsWidget.prototype._selectLocation = function(combo,selected) {

    if (combo == 'origin') {
        $('#departures').val(selected);
    }
    if (combo == 'destination') {
        $('#destinations').val(selected);
    }    
}

TravelDealsWidget.prototype._destinationCombo = function(target, id, what, data, selected){

    var $this = this;
    var $json = jQuery.parseJSON(data);
    var $select = $('<select style="width:135px" id="' + id + '" name="' + what + '">');
    var $default = $('<option value="">').html('Select ' + what + ' ...').appendTo($select);
    
    $.each($json.cities, function(i, city){
        var value = city.id + '_' + city.state + '_' + city.country;
        var option = $('<option value="' + city.airport + '">').html(city.label);
        option.appendTo($select);
    });
    
    if (selected) {
        $select.val(selected);
    }
    
    $select.change(function(i){
        
        if ($(this).val() != '') {
            
            var destination = $('#destinations').val();
            
            if ($(this).attr('name') == 'origin' && destination != '') {
                $this.refresh(target);
            }
            if ($(this).attr('name') == 'destination') {
                $this.refresh(target);
            }
        }
        
    });
    
    return $select;
    
}

TravelDealsWidget.prototype._propFillPopup = function(hotel_id, data){

    $.each(data, function(i){
        if (this.hotel == hotel_id) {
            $('#dealprop div.container a').html(this.name);
            $('#dealprop div.container a').attr('href', this.url);
            $('#dealprop div.container span.review_count').html(this.reviews);
            $('#dealprop div.container img').attr('src', this.img);
            $('#dealprop div.container #hotel_stars').attr('class', 'icon icon_stars_' + this.stars);
            $('#dealprop div.container #hotel_rating').attr('class', 'icon icon_reviews_' + this.rating);
        }
    });
    
    
}

TravelDealsWidget.prototype._propPopup = function(){

    var container = $('<div id="dealprop">');
    
    var dealsHtml = '<img src="' + this.protocol + 'images.wctravel.com/images-logos/10000999.jpg" border="0"><br>';
    dealsHtml += '<a href="#"></a><br>';
    dealsHtml += '<span id="hotel_stars"></span><span>Rating</span><br>';
    dealsHtml += '<span id="hotel_rating"></span><span class="review_count">0</span> <span>Reviews</span><br>';
    
    var hotel = $('<div>');
    hotel.attr('class', 'container');
    hotel.html(dealsHtml);
    hotel.appendTo(container);
    
    var arrow = $('<div>');
    arrow.attr('class', 'arrow');
    arrow.appendTo(container);
    
    container.hide();
    
    return container;
    
}

TravelDealsWidget.prototype._showProperties = function(l){

    var offset = $(l).offset();
    var top_position = offset.top - ($(".dealswidget #dealprop").outerHeight(true) / 2);
    var left_position = offset.left + $(l).outerWidth(true);
    
    if (top_position < $(window).scrollTop()) {
        top_position = $(window).scrollTop();
    }
    if ((top_position + $(".dealswidget #dealprop").outerHeight(true)) > ($(window).scrollTop() + $(window).height())) {
        top_position = ($(window).scrollTop() + $(window).height()) - $(".dealswidget #dealprop").outerHeight(true);
    }
    if ((left_position + $(".dealswidget #dealprop").outerWidth(true)) > $(window).width()) {
        left_position = offset.left - $(".dealswidget #dealprop").outerWidth(true);
        $(".dealswidget #dealprop").removeClass("right");
    }
    else {
        $(".dealswidget #dealprop").addClass("right");
    }
    
    $(".dealswidget #dealprop").css('top', top_position);
    $(".dealswidget #dealprop").css('left', left_position);
    
    $(".dealswidget #dealprop .arrow").css("top", ((offset.top + ($(".dealswidget .deals a").height() / 2)) - (top_position + ($(".dealswidget #dealprop .arrow").height() / 2))));
    
}

TravelDealsWidget.prototype._resultsContent = function(data){

    var $this = this;
    var row_results = $('<ul>');
    
    $.each(data, function(i){
    
        var label = $this._dealsLabel(this.label, this.url, this.saving, this.hotel, this.leading_price);
        var row = $('<li>').html(label);
        var odd = i % 2;
        
        if (odd == 0) {
            row.addClass('odd');
        }
        else {
            row.addClass('even');
        }

        row_results.append(row);

    });
    
    return row_results;
}

TravelDealsWidget.prototype._dealsLabel = function(text, url, saving, hotelid, leading_price){

    var link_container = $('<div>');
    link_container.css('width','65%');
    link_container.css('overflow','hidden');
    link_container.css('float','left');
    link_container.css('text-align','left');
    link_container.css('white-space','nowrap');
    
    var label = $('<b>').html(text);  
    
    if (url) {
        label = $('<a>').html(text);
       	if (this.src_aid){
       		if (hotelid){
       			url += '&src_aid=' + this.src_aid;
       		} else {
       			url = url.replace(/subAffiliateId=none/g, "subAffiliateId="+this.src_aid);
       		}
       	}
        label.attr('href', url);
        label.attr('target', '_blank');
        label.attr('name', hotelid);
    }
    
    label.appendTo(link_container);
    
    var price_container = $('<div>');
    price_container.css('width','30%');
    price_container.css('float','right');
    price_container.css('text-align','right');
    price_container.css('overflow','hidden');
    price_container.css('white-space','nowrap');

    
    if (saving || leading_price) {
        
        var txt = "Save " + saving + "%!";
        
        if (this.dealsMsg == 'price') {
            txt = "From $" + leading_price;
        }
        
        msg = $('<span>').html('&nbsp;' + txt)
        msg.appendTo(price_container);
    }
    
    return '&nbsp;'+link_container.clone().wrap('<div>').parent().html() + price_container.clone().wrap('<div>').parent().html();
}

TravelDealsWidget.prototype._generateTabs = function(has_hotels, has_flights, has_packages){

    var container = $('<ul>');
    
    if (has_hotels) {
        $('<li>').html(this._tabTagLink('hotel')).appendTo(container);
    }
    if (has_flights) {
        $('<li>').html(this._tabTagLink('flight')).appendTo(container);
    }
    if (has_packages) {
        $('<li>').html(this._tabTagLink('pkg')).appendTo(container);
    }
    
    return container;
    
}

TravelDealsWidget.prototype._tabTagLink = function(which){

    if (which == 'hotel') {
        return '<a href="#travel-deals-hotel">Hotel</a>';
    }
    if (which == 'flight') {
        return '<a href="#travel-deals-flight">Flight</a>';
    }
    if (which == 'pkg') {
        return '<a href="#travel-deals-flighthotel">Flight+Hotel</a>';
    }
    
}

TravelDealsWidget.prototype._generateAccordion = function(which, has_hotels, has_flights, has_packages){

    var container = $('<h3>').html(this._tabTagLink(which));
    
    if (which == 'hotel') {
        container.attr('class', 'first');
    }
    
    if (which == 'flight') {
        if ((!has_hotels && has_packages) || (!has_hotels && !has_packages)) {
            container.attr('class', 'first');
        }
        if (has_hotels && !has_packages) {
            container.attr('class', 'last');
        }
    }
    
    if (which == 'pkg') {
        if (has_hotels && has_flights) {
            container.attr('class', 'last');
        }
        else {
            container.attr('class', 'first');
        }
    }
    
    return container;
    
}

function include(filename){
    document.write('<script type="text/javascript" src="' + proto + domain + filename + '"></scr' + 'ipt>');
}

