/*
 *  Handles reading Nokia Maps download XML and generates links
 */

var xmlObject;
var urlPrefix;

$(document).ready(function() {
//Load the XML
	$.ajax( {
	  url: flashPath+'download_maps.xml',
		type: 'GET',
		dataType: 'xml',
		timeout: 10000,
		error: function(){
	    //alert('Error loading phone list \n Please try refreshing the page!');
   	},
		
		success: function(xml) {
		  xmlObject = $(xml);
		
			//The first part of the download URI:
			urlPrefix = $(xml).find('url_prefix').text();

			//How many phones are there?
			var numPhones = $(xml).find('array#models').children().length;

			//Let's split the phones into 3 columns to display more nicely
			var currentCol = 1;
			var currentPhone = 0;
			var boxNr = 1;
			
			$(xml).find('array#models').find('item').each(function() {
				
				if (currentPhone >= (numPhones / 2)) {
					boxNr = 2;
				}
				
				//get the name of the phone
				var phoneText = $(this).find('phone_id_txt').text();
        
        //downloadURL identifier
        var downloadURLID = $(this).find('download_url').text();

				//See is Nokia Maps is preinstalled on the phone => maps_version = s40_1
			  var preInstalled = $(this).find('maps_version').text();

				if (preInstalled.indexOf('s40_1') != -1) {
						$('<a href="javascript:void(0);"></a>').html(phoneText+" <br />").attr("href", "javascript:alert('Nokia Search is preinstalled on this device');" )
												.appendTo('div#box'+boxNr);
				} else {
						$('<a></a>').html(phoneText+" <br />").attr("href", "javascript:openPopUp('"+downloadURLID+"');")
												.appendTo('div#box'+boxNr);
				}
				
				//increment the phone counter for spliting the list properly
				currentPhone++;

			});
		}
	});
});

function openPopUp(urlID) {
  //download link
  var downloadLink = xmlObject.find('item#'+urlID).find('url').text();
  var popupToggle = xmlObject.find('item#'+urlID).find('popup').text();
  
  //open in the same window if not a pop-up
  if (popupToggle != 'false') {
    window.open(downloadLink,'','width=510,height=515');
  } else {
    window.location = downloadLink;
  }
}

