/* 
 * Single map display v3
 * By Andy Gale, http://andy-gale.com/
 * 
 * This really does look like line noise, doesn't it?
 * 
 * © GNC Broadcast Solutions Ltd 2009, All Rights Reserved
 */
 
// Var to be set by calling script
var myLat = null
var myLng = null
var myZoom = 14
var map = null
var geocoder = null
var amazon_id = null 
var affiliate_window_id = null
var buy_at_id = null
var tradedoubler_id = null
var zanox_id = null
var fixtures = null
var placeholders_url = null
var fixtures_url = null
var map_type = null
var clubs_url = null
var club_name = null
var club_id = null

// Private vars
var clubs = null
var placeholders = null
var fixtures = null

var setupInterval = null

$(document).ready(function(){	
	dd = new Date();
	ep = dd.getTime();
	
	$.getJSON(fixtures_url  + '?' + ep,
		function(fixtures_data){
			fixtures = fixtures_data
		})
		
	$.getJSON(placeholders_url + '?' + ep ,
		function(placeholders_data){
			placeholders = placeholders_data
		})
	
	if (map_type == 2) {
		$.getJSON(clubs_url + '?' + ep ,
			function(clubs_data){
				clubs = clubs_data
			})	
	}
	
	setupInterval = setInterval("setupMap()", 100)
	
	if (self == top)
		$('#bottom').remove()
})

function setupMap()
{
	if (map_type == 1 && placeholders != null && fixtures != null) {
		clearInterval(setupInterval)
		setupFixtureMap()
		$('#waitbox').remove()
	} else if (map_type == 2 && clubs != null && placeholders != null && fixtures != null) {
		clearInterval(setupInterval)
		setupClubsMap()
		$('#waitbox').remove()
	} 	
}

function setupFixtureMap()
{
	next_fixture = getNextFixture()

	var efs = document.getElementById('embedFormSelect')

    if (!efs)
        return

    efs.options.length = 0

    for (var i = 0; i < fixtures.length; i++) {
    
	    var optn = document.createElement("OPTION")

    	var date_str = ''

    	if (fixtures[i].when != null) {
    	    var nocent = parseInt(fixtures[i].when) - 20000000
        	var year = parseInt(nocent / 10000)
        	var noyear = parseInt(nocent - year * 10000)
        	var month = parseInt(noyear / 100)
        	var date = noyear - (month * 100)
        
        	date_str = (date < 10 ? '0' : '') + date + '/' + (month < 10 ? '0' : '') + month + '/' + (year + 2000) + ' - '
    	}

        optn.text = date_str + fixtures[i].who                
    
        optn.value = i
	    efs.options.add(optn)
	}
	
	if (next_fixture > -1) {
		efs.selectedIndex = next_fixture
		myLat = fixtures[next_fixture].where[0]
		myLng = fixtures[next_fixture].where[1]
		myZoom = fixtures[next_fixture].zoom
	}
	
	setupMapCommon()
}


function setupClubsMap()
{
	var next_fixture = getNextFixture()
		
	var efs = document.getElementById('embedFormSelect')
	if (!efs) {
   		return
	}
	
    efs.options.length = 0
    
    selected = -1
    
	preselected = null	
	if (self.location.search) {
		preselected = self.location.search.substr(1)
	} else if (self.location.hash) {
		preselected = self.location.hash.substr(1)
	}
	
    for (var i = 0; i < clubs.length; i++) {
    
	    var optn = document.createElement("OPTION")
    
        optn.text = clubs[i].name                
    
        optn.value = i
	    efs.options.add(optn)
	    
		if (preselected != null) {
			if (clubs[i].handle == preselected)
				selected = i
		} else if (next_fixture > -1 && clubs[i].id == fixtures[next_fixture].who_id) {
	    	selected = i
	    }
	}

	if (selected > -1) {
		efs.selectedIndex = selected
		myLat = clubs[selected].latitude
		myLng = clubs[selected].longitude
		myZoom = clubs[selected].zoom_level
	}

	setupMapCommon()
}

function setupMapCommon()
{
	// Setup map
	
	map = new GMap2(document.getElementById("map_canvas"))
  	map.setMapType(G_HYBRID_MAP);
  			 	
	map.addControl(new GLargeMapControl())
	map.addControl(new GMapTypeControl()) 

	center = new GLatLng(myLat, myLng)
	map.setCenter(center, parseInt(myZoom))

	// Setup placeholders
		
	var amazonRegEx = /http\:\/\/www\.amazon\.co\.uk\/dp\/(.+)?tag=([^\"]+)/
	var awinRegEx = /http:\/\/www\.awin1\.com\/awclick\.php\?mid=([^\&]+)\&amp;id=([^\"]+)/
	var awinCreadRegEx = /http:\/\/www\.awin1\.com\/cread.php\?awinmid=([^\&]+)\&amp;awinaffid=54468\&amp;clickref=\&amp;p=([^\"]+)/	
    var premierInnRegEx = /http:\/\/weekendbookings\.at\/footballdeals\?DURL=([^\"]+)/
	var ticketMasterRegEx = /http:\/\/ticketsuk\.at\/footballdeals\?([^\"]+)/
	
	
	var ibisRegEx          = /http:\/\/clkuk\.tradedoubler\.com\/click\?p\(31820\)a\(1481885\)g\(17086882\)([^\"]+)/
	var trainLineRegEx     = /http:\/\/clkuk\.tradedoubler\.com\/click\?p\(3447\)a\(1481885\)g\(27255\)/
	var hostelBookersRegEx = /http:\/\/clkuk\.tradedoubler\.com\/click\?p=34444\&a=1481885\&g=16167906([^\"]+)/
	
	var zanoxRegex = /http:\/\/ad\.zanox\.com\/ppc\/?([^\&]+)([^\"]+)/

	icons = []
	
	$.each(placeholders.types, function(i, item) {

		var icon = new GIcon(G_DEFAULT_ICON)
		icon.image = item.path

		mwidth = parseInt(item.width)
		mheight = parseInt(item.height)

		icon.iconSize = new GSize(mwidth, mheight);
		
		icons[i] = icon
	})

	markers = []
	
	$.each(placeholders.links, function(i,item){

		markerOptions = { icon: icons[item.type] };

		var desc = item.desc.replace(amazonRegEx, 'http://www.amazon.co.uk/dp/$1tag=' + amazon_id)   
		
		desc = desc.replace(awinRegEx, 'http://www.awin1.com/cread.php?awinmid=$1&awinaffid=$2&clickref=' +
							affiliate_window_id + '&p=')				
		desc = desc.replace(awinCreadRegEx, 'http://www.awin1.com/cread.php?awinmid=$1&amp;awinaffid=54468&amp;clickref=' + 									affiliate_window_id + '&amp;p=$2')		
		desc = desc.replace(premierInnRegEx, 'http://weekendbookings.at/footballdeals?LID=' + 
							buy_at_id + '&amp;DURL=$1')
		desc = desc.replace(ticketMasterRegEx, 'http://ticketsuk.at/footballdeals?LID=' + buy_at_id + '&amp;')
		desc = desc.replace(ibisRegEx, 'http://clkuk.tradedoubler.com/click?p(31820)a(1481885)g(17086882)epi(' + 
							tradedoubler_id + ')$1')
		desc = desc.replace(trainLineRegEx, 'http://clkuk.tradedoubler.com/click?p(3447)a(1481885)g(27255)epi(' + 
							tradedoubler_id + ')')			
		desc = desc.replace(hostelBookersRegEx, 'http:\/\/clkuk\.tradedoubler\.com\/click\?p=34444\&a=1481885\&g=16167906\&epi=' + tradedoubler_id + '$1')					
		desc = desc.replace(zanoxRegex, 'http://ad.zanox.com/ppc/\?' + zanox_id + '$2')

		var marker = new GMarker(new GLatLng(item.lat, item.long), markerOptions)

		GEvent.addListener(marker, "click", function() {
	        marker.openInfoWindowHtml('<h1>' + item.name + '</h1>' + desc, { maxWidth: 350 })

		});
	    
		markers.push(marker)
	})

	var mgr = new MarkerManager(map)
	
  	mgr.addMarkers(markers, 0)
  	mgr.refresh()
  	
  	$('#embedForm').submit(function () {
		tryGeoCode()
		return false
	})

	$('#lookupButton').click(function() { tryGeoCode() })
	
	$('#SchemeLinkGeocode').click(function() {
		
		if ($('#SchemeLinkGeocode').val() == 'Find place') {
			$('#SchemeLinkGeocode').val('')
		}

	})
	
	$('#embedFormSelect').change(function() { jumpMapToFixture() })

	$('#largerlink').attr('href', self.location.href)
}

function getNextFixture()
{			
	var cur = 0
			
// Make a date string so it's like the one we've got
	var n = new Date()
	
    // Deal with older browsers
    var year = n.getFullYear()
    if (year < 2000) {
        year += 1900;
    }
        
    // month is helpfully 0-11 don't forget
    var month = n.getMonth() + 1
    if (month < 10)
        month = '0' + month
            
    var mday = n.getDate()
    if (mday < 10)
        mday = '0' + mday
        
    //var now_int = 20091008 //<-- uncomment for test
   	var now_int = parseInt(year + '' + month + '' + mday)

    // work out cur (current fixture)
        
    for (var i = 0; i < fixtures.length; i++) {
        if (fixtures[i].when != null && fixtures[i].when < now_int)
            cur++
    }

	return cur
}

function tryGeoCode()
{		
	text = $('#SchemeLinkGeocode').val()
	
	if (!geocoder) {	
		geocoder = new GClientGeocoder()
		geocoder.setBaseCountryCode('uk')
	}
			
	geocoder.getLatLng(text, function(latlng) { 
		map.setCenter(latlng, 16)
	})
}

function jumpMapToFixture()
{
	var efs = document.getElementById('embedFormSelect')
	var pos = efs.selectedIndex
	
	if (map_type == 1) {	
		center = new GLatLng(fixtures[pos].where[0], fixtures[pos].where[1])
		map.setCenter(center, parseInt(fixtures[pos].zoom))
	} else if (map_type == 2) {
		center = new GLatLng(clubs[pos].latitude, clubs[pos].longitude)
		map.setCenter(center, parseInt(clubs[pos].zoom_level))
	}
}

$(document).unload(function(){ GUnload() })
