/**
* Load widget data from ajax.tv2.dk into cookie bar
*
* Todo:
* 1. Change ajax.tv2.dk/vejret/place.php to send json back
* 2. Change cookie.js to handle things like this demo, using ids and indexes
* 3. ????
* 4. Profit.
*/
$(document).ready(function() {
    var serviceUrl      = 'http://' + TV2.getSite('ajax')+'/vejret/place.php';
    var cookieName      = 'WeatherLocationHistory';

    var places          = [];

    // Get toponym id from url
    var match           = window.location.toString().match(/\/vejr\/id-([0-9]+)/);
    if(match && match.length && match.length > 1 && match[1]) {
        places.push(match[1]);
    }
    // Get toponym ids from cookie
    var cookiePlaces    = $.cookie(cookieName)?$.cookie(cookieName).split(','):[];
    places = places.concat(cookiePlaces);

    // Get a list of default toponyms 
    var defaultPlaces = $('ul#w-widget-history li');
    defaultPlaces.each(function(i, li){
        places.push(li.id.replace('place-', ''));
    });

    // Prune duplicates, prioritizing url > cookie > default
    var unique  = [];
    var l = places.length;
    for(var i=0; i<l; i++) {
        var u   = unique.length;
        var un  = true;
        for(var j=0; j<u; j++) {
            if(places[i] == unique[j]) {
                un=false;
            }
        }
        if(un === true) {
            unique.push(places[i]);
        }
    }

    // Write updated history list to cookie
    $.cookie(cookieName, unique.slice(0, defaultPlaces.length).toString(), { path: '/', expires: 3650, domain: 'tv2.dk' });

    // Then repopulate the history list with richer ajax data
    if(match) {
        cookiePlaces = unique.slice(1, unique.length) ; // skip the first place (this page)
    } else {
        cookiePlaces = unique.slice(0, unique.length) ;
    }
    $('ul#w-widget-history li').each(function(i, li) {
        if(cookiePlaces.length > i && cookiePlaces[i]) {
            li.id = 'place-'+parseInt(cookiePlaces[i]);
        } else {
            return;
        }
        $.ajax({
            url             : serviceUrl,
            dataType        : 'jsonp',
//            jsonpCallback   : 'jsonp_'+li.id.replace('-','_'),
            data            : {
                                id          : li.id.replace('place-','')
                              },
            success         : function(data) {
                                var li = $('ul#w-widget-history li#place-'+data.id);
                                if(data.id && data.name && data.canonical && data.temperature && data.symbol && data.symbol.src && data.symbol.title) {
								//	alert("Name=" + data.name + " --- " + data.canonical);
                                    var a = $("<a></a>").attr('href', data.canonical );
                                    a.append($("<strong>"+data.name+"</strong>"));

                                    var symbol = $("<img></img>");
                                    symbol.attr({
                                        src : data.symbol.src,
                                        alt : data.symbol.title
                                    });
                                    a.append(symbol);

                                    a.append($("<span>"+Math.round(data.temperature, 2)+"&#176;</span>"));
                                    li.empty();
                                    li.append(a);
                                } else {
                                    li.remove();
                                }
                              }
        });
    });
});

