// #######################
// Events Tab
// #######################

(function ($) {
    $.getJSON('includes/nusoap/ski_events.php', function(data){

        var 
        result = data.SearchResult,
        results_len = result.length,

        ski = $('.ski-events').length,
        family = $('.family-events').length,
        food = $('.food-events').length,
        romance = $('.romance-events').length,

        insert = function (startDate, month, day, title, description, website) {
            var 
            title = website ? '<a href="' + website + '" target="_blank">' + title + '</a>' : title,
            insert = '<li data-date="' + startDate + '" class="clearfix tab-list-item"><ul><li class="loaded-date"><ul><li class="loaded-month">' + month + '</li><li class="loaded-day">' + day + '</li></ul></li><li class="loaded-copy"><h2>' + title + '</h2><p>' + description + '</p></li></ul></li>';
            return insert;
        },

        getEventDetails = function(item) {
            var 
            title = item.Name,
            shortDesc = item.ShortDescription,
            startDate = new Date(item.StartDate),
            month = startDate.format('M'),
            day = startDate.format('d');

			try {
				website = item.Websites.Website['@attributes'].Url;
				var 
				http = website.indexOf('http://'),
				https = website.indexOf('https://');
				
				if( http === -1 || https === -1 ){
					website = 'http://' + website;
				}
			} catch (error) { 
				website = undefined;
			}
			
            return {
                title:title,
                shortDesc:shortDesc,
                startDate:startDate,
                month:month,
                day:day,
				website: website
            }
        },

        oc = function (a) {
            var o = {}, a_len = a.length;
            for( var i = 0; i < a_len; i += 1) {
                o[a[i]]='';
            }
            return o;
        },
        skiing_cat = oc(['Sport', 'Skiing', 'Spectator Event']),
        family_cat = oc(['Watchable Wildlife', 'Fireworks', 'Spectator Event', 'Aquatic', 'Parade', 'Holiday', 'Festival', 'Supper', 'Family Entertainment', 'Carnival', 'Kids Activities']),
        food_cat = oc(['Breakfast', 'Lunch', 'Supper', 'Food', 'Culinary', 'VT Products', 'Winery/Brewery']),
        romance_cat =  oc(['Festival', 'Fireworks', 'Carnival', 'Parade', 'Literary Reading', 'Supper', 'Music-Pop/Rock', 'Tour', 'Music-Country', 'Music-Classical', 'Music-Bluegrass', 'Music-Folk', 'Music-Acoustic', 'Music-Blues', 'Music-Jazz', 'Music-Choir', 'Theater-Comedy', 'Theater-Opera', 'Theater-Drama', 'Exhibit', 'Theater-Musical', 'Theater-Performance Art', 'Film', 'Dance Performance', 'Open Studio Weekend', 'Antique', 'Food', 'Spectator Event', 'VT Products', 'Winery/Brewery', 'Culinary', 'Holiday', 'Historic']);

        for ( var i = 0; i < results_len; i++ ) {
            
            var
            item = result[i],
            service_types = item.ServiceTypes.ServiceType,
            service_types_len = service_types.length;

            if (service_types_len > 0) {
                for ( var j = 0; j < service_types_len; j++) {

                    var 
                    description = service_types[j]['@attributes'].Description,
                    seen = {};
                    
                    // ski
                    if ( ski ) {
                        if ( description in skiing_cat ) {
                            var items = getEventDetails(item); 
                            $('.ski-events').append(insert(items.startDate, items.month, items.day, items.title, items.shortDesc, items.website));
                        }
                    }
                    // family
                    else if ( family ) { 
                        if ( description in family_cat ) {
                            
                            var items = getEventDetails(item);
                            $('.family-events').append(insert(items.startDate, items.month, items.day, items.title, items.shortDesc, items.website));

                        }
                    }
                    // food
                    else if ( food ) {
                        if ( description in food_cat ) {
                            
                            var items = getEventDetails(item);
                            $('.food-events').append(insert(items.startDate, items.month, items.day, items.title, items.shortDesc, items.website));

                        }
                    }
                    // romance
                    else if ( romance ) {
                        if ( description in romance_cat ) {

                            var items = getEventDetails(item);
                            $('.romance-events').append(insert(items.startDate, items.month, items.day, items.title, items.shortDesc, items.website));

                        }
                    }

                    $('.event-load').remove();

                    $('.tab-list-item').each(function() {
                        var txt = $(this).text();
                        if (seen[txt]) {
                            $(this).remove();
                        } else {
                            seen[txt] = true;
                        }
                    });
			
					
                }
            }
        }
	
// Sort

(function () {
	var lis_bucket = [],
		lis_list = $('li.tab-list-item'),
		list_length = lis_list.length,
		ul = $('.events-content'),
		today = new Date(),
		i = 0;

	for (i = 0; i < list_length; i += 1) {
		lis_bucket[i] = [];
		lis_bucket[i][0] = new Date($(lis_list[i]).attr('data-date'));
		lis_bucket[i][1] = $(lis_list[i]).remove();
	}

	lis_bucket.sort(function (a, b) {
		return a[0] - b[0];
	});

	for (i = 0; i < list_length; i += 1) {
		if (today < lis_bucket[i][0]){
			ul.append(lis_bucket[i][1]);
		}
	}

}());
			
});


    // Simulates PHP's date function
    // SLIMMED DOWN
    Date.prototype.format = function(format) {
        var returnStr = '';
        var replace = Date.replaceChars;
        for (var i = 0; i < format.length; i++) {       
            var curChar = format.charAt(i);         
            if (i - 1 >= 0 && format.charAt(i - 1) == "\\") {
                returnStr += curChar;
            }
            else if (replace[curChar]) {
                returnStr += replace[curChar].call(this);
            } else if (curChar != "\\"){
                returnStr += curChar;
            }
        }
        return returnStr;
    };

    Date.replaceChars = {
        shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        // Day
        d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
        // Month
        M: function() { return Date.replaceChars.shortMonths[this.getMonth()]; }
    };

	
		
})(jQuery);

