/* global vars */
var layers = {};
var photoItens = 15;
var videoItens = 15;

var icons = function() {
    retValue = {}
    kinds = ['sales', 'rentals', 'photos', 'videos']
    
    for (kind in kinds) {
        retValue[kinds[kind]] = new GIcon();
        retValue[kinds[kind]].image = "resources/images/icon_" + kinds[kind] + ".png";
        retValue[kinds[kind]].iconSize = new GSize(24, 25);
        retValue[kinds[kind]].iconAnchor = new GPoint(12, 25);
        retValue[kinds[kind]].infoWindowAnchor = new GPoint(12, 5);
    }
    return retValue;
}();



/* loads google maps */
function mapLoad() {


	if (GBrowserIsCompatible())
	{
		map = new GMap2(document.getElementById("themap"));
		map.setCenter(new GLatLng(40.749395,-73.970057),19);

		map.addControl(new GMapTypeControl());
		map.addControl(new GLargeMapControl());
		map.addControl(new GScaleControl());
		map.setMapType(G_HYBRID_MAP);

		map.checkResize();
		createLayers();
		activateChecks();
		activeModalLinks();
	}
	else
		alert('Your browser is not compatible with Google Maps');

}


function createLayers() {
    
    layers['rentals'] = {
        type: 'overlay',
        data: new GGeoXml('http://maps.google.com/maps/ms?ie=UTF8&hl=en&oe=UTF8&msa=0&msid=111611717116094002466.00047f21da16950706780&output=kml')
    }
    
    layers['sales'] = {
        type: 'overlay',
        data: new GGeoXml('http://maps.google.com/maps/ms?ie=UTF8&hl=enc&oe=UTF8&msa=0&msid=111611717116094002466.00047f2221ae5c800b2bb&output=kml')
    }
    
    layers['photos'] = {
        type: 'manager',
        data: []
    }
    createPhotosArray();
    
    layers['videos'] = {
        type: 'manager',
        data: []
    }
    createVideosArray();


    layers['wikipedia'] = {
        type: 'overlay',
        data: new GLayer("org.wikipedia.en")
    }
    
    
}

function createMarker(coords, html, icon) {
    var marker = new GMarker(coords, { icon:icons[icon]});

    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(html);
    });
    
    return marker;
}

function isBlockedItem(service, owner, itemId) {

    if (typeof(block[service]) == 'undefined')
        return false;
    
    if (typeof(block[service]['user']) != 'undefined')
        for (blockedIndex=0; blockedIndex<block[service]['user'].length; blockedIndex++)
            if (block[service]['user'][blockedIndex] == owner)
                return true

    if (typeof(block[service]['post']) != 'undefined')
        for (blockedIndex=0; blockedIndex<block[service]['post'].length; blockedIndex++)
            if (block[service]['post'][blockedIndex] == itemId)
                return true

    return false;
}


function createPhotosArray(page) {
    if (typeof(page) == "undefined")
        page = 1;
        
    $.getJSON('http://api.flickr.com/services/rest/?method=flickr.photos.search&format=json&api_key=b9ba04296cf1c927b50cb6db4d71d18d&text=%22tudor+city%22&per_page=50&extras=geo,date_taken,owner_name,description&sort=date-taken-desc&page='+page+'&jsoncallback=?',
        function(data){
            processPhotosArray(data);
            readChecks();
        }
    );
}

function processPhotosArray(data) {
    var okToShow = 0;

    for (photoIndex=0; okToShow<photoItens; photoIndex++) {
        var photo = data.photos.photo[photoIndex]
        
        if (isBlockedItem('flickr', photo.ownername, photo.id))
            continue;
        
        if (photo.title.toLowerCase().indexOf('tudor city') == -1 
        && photo.description._content.toLowerCase().indexOf('tudor city') == -1)
            continue;
        
        if (photo.latitude && photo.longitude) {
            coords = new GLatLng(photo.latitude, photo.longitude)
        }
        else
            coords = genRandCoords();
            
        if (photo.description._content > 250)
            description = photo.description._content.substr(0,250) + "...";
        else {
            description = photo.description._content;
            
            if (description.length < 50)
                descriptionWidthClass = 'fixed'
            else
                descriptionWidthClass = ''
        }

            
        var bubbleContent = '\
        <div class="bubble_content"> \
            <p class="title">' + photo.title + '</p> \
            <a class="act_modal" href="http://farm' + photo.farm + '.static.flickr.com/' + photo.server + '/' + photo.id + '_' + photo.secret + '.jpg" target="_blank" title="' + photo.title + ' - <a href=\'http://www.flickr.com/photos/' + photo.owner + '/' + photo.id + '/\' target=\'_blank\'>See on Flickr</a>"><img  class="thumb" src="http://farm' + photo.farm + '.static.flickr.com/' + photo.server + '/' + photo.id + '_' + photo.secret + '_s.jpg" height="90" width="120"></a> \
            <p class="description ' + descriptionWidthClass + '">' + photo.description._content + '</p> \
            <p class="author">By ' + photo.ownername + '</p> \
            <p class="date">' + photo.datetaken + '</p> \
        </div>';

        var marker = createMarker(coords, bubbleContent, 'photos');
        GEvent.addListener(marker, 'infowindowopen', function(){activeModalLinks();});
        
        layers['photos']['data'].push(marker);
        map.addOverlay(marker);
        
        okToShow++;
    }


}

function createVideosArray() {
    $.getJSON('http://gdata.youtube.com/feeds/api/videos?alt=json-in-script&q=%22tudor+city%22&orderby=published&max-results=50&callback=?',
        function(data){
                processVideosArray(data);
                readChecks();
            }
    );
}

function processVideosArray(data){
    var okToShow = 0;
    
    for (movieIndex=0; okToShow<videoItens; movieIndex++) {
        var movie = data.feed.entry[movieIndex];
        
        if (isBlockedItem('youtube', movie.author[0].name.$t, movie.id.$t.substr(movie.id.$t.lastIndexOf('/')+1)))
            continue;
        
        if (typeof(movie.georss$where) == 'object') {
            coordsArray = movie.georss$where.gml$Point.gml$pos.$t.split(" ");
            coords = new GLatLng(coordsArray[0], coordsArray[1]);
        }
        else
            coords = genRandCoords();
        
            
        if (movie.content.$t.length > 250) {
            description = movie.content.$t.substr(0,250) + "...";
            descriptionWidthClass = ''
        }
        else {
            description = movie.content.$t;
            
            if (description.length < 50)
                descriptionWidthClass = 'fixed'
            else
                descriptionWidthClass = ''
        }
        
        var bubbleContent = '\
        <div class="bubble_content"> \
            <p class="title">' + movie.title.$t + '</p> \
            <a href="#youtube_player" id="inline" class="act_modal"><img src="' + movie.media$group.media$thumbnail[0].url + '" height="90" width="120" class="thumb"></a> \
            <p class="description ' + descriptionWidthClass + '">' + description + '</p> \
            <p class="author">By ' + movie.author[0].name.$t + '</p> \
            <p class="date">' + movie.published.$t + '</p> \
            <div class="hide"> \
                <div id="youtube_player"> \
                    <object width="480" height="385"><param name="movie" value="' + movie.media$group.media$content[0].url + '&autoplay=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="' + movie.media$group.media$content[0].url + '&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object> \
                    <div><a href="' + movie.media$group.media$player[0].url + '" target="_blank">See on YouTube</a></div> \
                </div> \
            </div> \
        </div>';
        
        var marker = createMarker(coords, bubbleContent, 'videos');
        GEvent.addListener(marker, 'infowindowopen', function(){activeModalLinks();});
        
        layers['videos']['data'].push(marker);
        map.addOverlay(marker);
        
        okToShow++;
    }
}

function activeModalLinks(){
    $('a.act_modal').fancybox({
        autoScale:true,
        titleShow:true,
        titlePosition:'over'
    });
}



function readChecks() {
    $("input[id^='check_']").each(function() {
        toggleLayer(this.checked, $(this).attr('name').substr(6));
    })
}

function activateChecks() {
    $("input[id^='check_']").click(function() {
        toggleLayer(this.checked, $(this).attr('name').substr(6));
    });
}

function toggleLayer(show, layerName) {
    layer = layers[layerName]
    if (layer['type'] == 'overlay') {
        if (show)
            map.addOverlay(layer['data']);
        else
            map.removeOverlay(layer['data']);
    } else {
        for (var item=0; item<layer['data'].length; item++) {
            if (show)
                layer['data'][item].show()
            else
                layer['data'][item].hide()
        }
    }
}

function genRandCoords() {
    midLat = 40.748712;
    midLon = -73.971618;
    latPow = 0.003;
    lonPow = 0.005;
    return new GLatLng(midLat+((Math.random()-0.5)*latPow),midLon+((Math.random()-0.5)*lonPow));
}

