
/**
 * This function checks the CSS properties to see if the element is actually
 * visible to the user. 
 */
function invisibleParent(obj) {
  if (obj == document) return null;
  if (!obj) return null;
  if (!obj.parentNode) return null;
  if (obj.style) {
      if (obj.style.display == 'none') return obj;
      if (obj.style.visibility == 'hidden') return obj;
  }

  //Try the computed style in a standard way
  if (window.getComputedStyle) {
      var style = window.getComputedStyle(obj, "");
      if (style.display == 'none') return obj;
      if (style.visibility == 'hidden') return obj;
  }

  //Or get the computed style using IE's proprietary way
  var style = obj.currentStyle;
  if (style) {
    if (style['display'] == 'none') return obj;
    if (style['visibility'] == 'hidden') return obj;
  }
  return invisibleParent(obj.parentNode);
}

/**
 * Used by test-drive Flash to open URLs with Hash linking to the same page as the Flash
 * (Downloads & Services page)
 * @param url url string fetched by the Flash from the XML
 */
function openHashURL(url) {
  location.href=url;
  if(location.href.indexOf(url) != -1) {
      window.location.reload();
  }
}

/**
 * Namespace containing functions used on the Downloads & Services page
 */
var OviMapsFunctions = {
  //operating system - 'mac' | 'win'
  systemOS : 'win',
  
  /**
   * Checks whether the user is using MacOS
   * and sets the OviMapsFunctions.systemOS 
   * variable accordingly
   */
  detectOS : function() {
    //$('#download-steps-2-and-3 .grey-content-block-wide .wide-block-content .info-text').show();
		OviMapsFunctions.systemOS = "win";
		
    if (navigator.appVersion.indexOf("Win")!=-1) {
			OviMapsFunctions.systemOS = "win";
			$('#download-wizard-text-win-map-loader').show();
			$('#download-wizard-text-mac-map-loader').hide();
		}
    if (navigator.appVersion.indexOf("Mac")!=-1) {
			OviMapsFunctions.systemOS = "mac";
			$('#download-wizard-text-mac-map-loader').show();
			$('#download-wizard-text-win-map-loader').hide();
      $('#download-wizard-text-mac-maps').show();
		}
    //document.write('Your OS: '+OSName);
		
    //if (navigator.appVersion.indexOf("Mac")!=-1) OviMapsFunctions.systemOS="mac";
		// update sIFR
		replace_sIFR_3();
		
  },

  /**
   * Toggle the Terms & Conditions display
   * TnC is located within element with id="#download-tnc"
   * When the TnC is shown, the download maps / download map loader containers
   * are hidden
   */
  toggleTnC : function(action, callerEl) {
    var tnc = $('#download-tnc');
    if (action == 'close') { 
      tnc[0].style.display = 'none'; 
      $('#download-steps-2-and-3')[0].style.display='block';
      scrollToElement(callerEl);
    } else if (action == 'open') {
      //debugLog("Opening TnC");
      tnc[0].style.display = 'block';
      $('#download-steps-2-and-3')[0].style.display='none';
      scrollToElement(tnc[0]);
    }
    replace_sIFR_3();
  },


  //Currently selected device
  selectedDev : null,

  /**
   * Generates a hbx.mlc from two strings, assuming that mlc1 is the first part of the mlc
   * and may be used for double tagging - therefore including multiple mlc's separated by ';'
   * second part is then appended to each of the original mlcs, and the result concateated together.
   * example mlc1 = "mlcA;mlcB", mlc2 = "/foo/bar" 
   * function output = "mlcA/foo/bar;mlcB/foo/bar"
   *
   * @param mlc1 complete hbx.mlc as defined on the page
   * @param mlc2 string that have to be appended to the original hbx.mlc
   */
  generateMlc : function(mlc1, mlc2) {
    var marr = mlc1.split(';');
    var full = '';
    for (i=0; i<marr.length; i++) {
      full += marr[i] + mlc2;
      if (i+1 != marr.length) {
        full += ';'
      }
    }
    //debugLog(full);
    return full;
  },

  /**  
   * Device list mouse-click handler - called when user clicks on any of the devices 
   * in Ovi Maps Download Flash
   * 
   * @param device String, device name
   * @param version String, maps version ('s60_2', 's60_3' or 's40_1')
   * @param download_url String, URI of the installation file for the selected device
   * @param extra_info Boolean, specifies whether device needs to have additional 
   * instructions displayed. Such devices have the <show_infostep>1</show_infostep> node
   * in devices_ovi_maps.xml file
   * 
   * Displays the device specific version  text
   */
  deviceSelected : function(device, version, download_url, extra_info) {
    //debugLog("Device: "+device+" , Version: "+version+" , Download URL: "+download_url+" , Extra info: "+extra_info);
    if (typeof hbx ==  "object") {
      if (hbx.mlc != undefined) {
        var hbxMlc = hbx.mlc;
      } else {
        var hbxMlc = false;
      }
    } else {
      var hbxMlc = false;
    }
    //replace spaces with "+"
    var hbxDevice = device.replace(/\s/ig, "+");
    //strip non-alphanumeric characters
    hbxDevice = hbxDevice.replace(/[^a-zA-Z+0-9]+/g,'');
    //record device for HBX
    if (hbxMlc != false) _hbPageView(hbxDevice, OviMapsFunctions.generateMlc(hbxMlc, '/download/'+hbxDevice));
    //hide all download wizard boxes
    $('.download-wizard').each(function() { $(this)[0].style.display="none"; });
    
    if (download_url != null)
      var installationFile = download_url;
		
		if($("#map-updater-steps").hasClass("close")) {
			$("#map-updater-steps").addClass("active");
			$("#map-updater-steps").removeClass("close");
			$(".info-text").hide();
			$("#download-maps-updater").slideToggle(400);
		}
    
    //debugLog("hbxMlc " + hbxMlc);
    
    //filename only (without the path)
    if (download_url != null)
     var fileHbx = installationFile.replace(/.*\//g, '');
    
    //hbx function for download button - called by setTimeout
    //Records the filename of the file being downloaded to HBX
    if (hbxMlc != false && download_url != null ) {
      hbxDownloadFn = "_hbPageView('"+fileHbx+"','"+
        OviMapsFunctions.generateMlc(hbxMlc, '/download/'+OviMapsFunctions.systemOS+'/'+version+'/'+fileHbx)+"')";
    }
    //debugLog("hbxDownloadFn: " + hbxDownloadFn);

    //debugLog("OviMapsFunctions.systemOS: "+OviMapsFunctions.systemOS);
    //If MacOS is detected, show MacOS info if Ovi Maps 3.0 or Nokia Maps 2.0 device is selected
    if (OviMapsFunctions.systemOS == 'mac' && (version == 's60_3' || version == 's60_2')) {
       $('#download-wizard-text-mac-maps')[0].style.display="inline";
       //Show Nokia Maps 2.0 label if Maps 2.0 device is selected
			 if (version == 's60_2') {
				 $('#download-wizard-text-mac-maps').find("#hdr-3").hide();
				 $('#download-wizard-text-mac-maps').find("#hdr-2").show();
       //otherwise show Ovi Maps 3.0 label
			 } else { 
				 $('#download-wizard-text-mac-maps').find("#hdr-3").show();
				 $('#download-wizard-text-mac-maps').find("#hdr-2").hide();
			 }
       //Enable link for switching from MacOS to Windows (to make Windows download files available)
       $('#download-mac-os-toggle').click(function() {
             OviMapsFunctions.systemOS='win';
             OviMapsFunctions.deviceSelected(device, version, download_url, extra_info);
           });
    //otherwise show Windows specific information
    } else {
      
      //toggle Maps-version-specific download details / file location
      switch(version) {
        //Ovi Maps 3.0
        case 's60_3' :
          //if additional instructions are needed for device:
          //(marked by <show_infostep>1</show_infostep> in the download XML)
          if (extra_info) {
            $('#download-wizard-text-win-maps-3-special')[0].style.display="inline";
            $('#download-btn-maps-3-special').attr('href', installationFile);
            $('#download-btn-maps-3-special').unbind("click").click(function() {
                if (hbxMlc != false)
                    //attach HBX hit to a timeout (otherwise the HBX call conflicts with download action
                    setTimeout(hbxDownloadFn, 1300);
                });
            $('#device-name-replacable').text(device);
          } else {
            $('#download-wizard-text-win-maps-3')[0].style.display="inline";
            $('#download-btn-maps-3').attr('href', installationFile);
            $('#download-btn-maps-3').unbind("click").click(function() {
                if (hbxMlc != false)
                    setTimeout(hbxDownloadFn, 1300);
                });
          }
          break;
        //Nokia Maps 2.0
        case 's60_2' :
          $('#download-wizard-text-win-maps-2')[0].style.display="inline";
          $('#download-btn-maps-2').attr('href', installationFile);
          $('#download-btn-maps-2').unbind("click").click(function() {
              if (hbxMlc != false)
                setTimeout(hbxDownloadFn, 1300);
              });
          break;
      }
    }
    //Nokia Maps for S40 doesn't offer download functionality, so is the same 
    //for both Windows and MacOS
    if (version == 's40_1') {
      $('#download-wizard-text-win-maps-s40')[0].style.display="inline";
    }
		// update sIFR
		replace_sIFR_3();
  },

  /**
   * When called, this function prints the End User License Agreement
   * as formated in the div element with id "download-tnc-terms".
   */
  printTnC : function() { 
    var sOption="toolbar=no,location=no,directories=no,menubar=no,"; 
        sOption+="scrollbars=yes,width=750,height=600,left=100,top=25"; 

    var sWinHTML = document.getElementById('download-tnc-terms').innerHTML; 
   
    var winprint=window.open("","",sOption); 
    winprint.document.open(); 
    winprint.document.write('<html><head><title>Ovi Maps 3.0 - Software Disclaimer</title>'+
     '<link href="http://europe.nokia.com/css/style_r41.css" rel="stylesheet" type="text/css" />'+
     '</head><body style="text-align: left">'); 
    winprint.document.write(sWinHTML);          
    winprint.document.write('</body></html>'); 
    winprint.document.close();
    winprint.print();
    winprint.close();
    winprint.focus(); 
  },

  /**
   * Reads <UL> list with id=map-loader-countries and
   * populates the <select> with id=map-loader-countries-sel
   *
   * @param langSelected String, Language selected from the 
   * language selection dropdown
   */
  populateMapLoaderSelector : function(langSelected) {
    //var mapLoaderSel = $('#map-loader-countries-sel');
    $('#map-loader-countries-list li a').each(function() {
      var optHTML = '<option ';
      if (langSelected === $(this).text()) optHTML += 'selected="selected" ';
      optHTML += 'value="' + $(this).attr('href') + '">' + $(this).text() + '</option>';
      $(optHTML).appendTo('#map-loader-countries-sel');
    });
  },
  
  /**
   * Downloads the Map Loader file corresponding to the currently selected language
   */
  downloadMapLoader : function() {
    //window.open($('#map-loader-countries-sel').attr('value'),"","");
    var fileLocation = $('#map-loader-countries-sel').attr('value');
    location.href = fileLocation;
    //get the file name
    fileLocation = fileLocation.replace(/.*\//g, '');
    if (typeof hbx ==  "object") {
      if (hbx.mlc != undefined) {
        var hbxMlc = hbx.mlc;
      } else {
      var hbxMlc = false;
      }
    } else {
      var hbxMlc = false;
    }
    if (hbxMlc != false) _hbPageView(fileLocation, OviMapsFunctions.generateMlc(hbxMlc, '/map+loader/'+fileLocation));
  },

  /**
   * Toggle between Map Loader for Windows / Mac OS display
   *
   * @param os String, 'win' or 'mac' specifies the OS for which to display
   * Map Loader information
   */
  toggleMapLoaderOS : function(os) {
    if(os === 'mac') {                            
      $('#download-wizard-text-win-map-loader')[0].style.display="none";
      $('#download-wizard-text-mac-map-loader')[0].style.display="block";
      replace_sIFR_3();
    } else {
      $('#download-wizard-text-mac-map-loader')[0].style.display="none";
      $('#download-wizard-text-win-map-loader')[0].style.display="block";
      replace_sIFR_3();
    }
  }
}

//holds the tab-linking info  
var tabLinks = {};
//get hashname from the URL
tabLinks.hashName = location.hash;
//alert(location.hash);

/* get the outer parent of the element with id=location.hash */
tabLinks.p = invisibleParent($(tabLinks.hashName)[0]);
if($(tabLinks.p).attr('id') == tabLinks.hashName.substring(1) && (tabLinks.hashName.indexOf('#') != -1)) {
  tabLinks.p = invisibleParent(tabLinks.p.parentNode);
  //alert("1");
}
/* outer parent id */
tabLinks.parentId = $(tabLinks.p).attr('id');
//debugLog("Parent ID of selected tab: " + tabLinks.parentId);

$(function() {
  //1) Download tab:
  //hide Ovi Maps download container
  $("#map-updater-steps").addClass("close");
  //hide Map Loader container
  $("#map-loader-steps").addClass("close");
	
  $("#download-maps-updater").hide();
	$("#download-maps-loader").hide();
	$(".info-text").hide();



  //2) Premium Services tab:
	//$(".empty-grey-block").hide();
  //hide Services for Nokia Maps 2.0 section:
	$("#maps-2-tab-container").hide();
  //hide Services for Nokia Maps on S40 section:
	$("#maps-s40-tab-container").hide();

  /**
   * Open / Close functionality for Ovi Maps pages tabs
   * on click function toggles close class and hide / show tabs content 
   */
		 
  //Download Maps updater steps
  $("#map-updater-steps").click(function() {
		if($("#map-updater-steps").hasClass("active")) {
	    $("#download-maps-updater").slideToggle(400);
		  $(this).toggleClass("close");
		}
		else {
			$(".info-text").slideDown(400);
		}
  });
	
	//Download Maps loader steps
	$("#map-loader-steps").click(function() {
	  $("#download-maps-loader").slideToggle(400,
		function(){ 
		if($("#map-loader-steps").hasClass("close")) {
		  replace_sIFR_3();
	  }
		$("#map-loader-steps").toggleClass("close");
		});
  });
	
  	/**
   * Open / Close functionality for Premium services pages tabs
   * on click function toggles close class and hide / show tabs content 
   */
		 
	//Services for Ovi Maps 3.0 tab
	$("#services-maps-3").click(function() {
		if($(this).hasClass("close")) {
			$(this).parent().parent().parent().find(".empty-grey-block").toggleClass("close");
			$("#maps-3-tab-container").slideToggle(400);
		}
		else {
			$("#maps-3-tab-container").slideToggle(400, 
		  function(){ 
		    $("#services-maps-3").parent().parent().parent().find(".empty-grey-block").toggleClass("close");
		  });  
		}
		$(this).toggleClass("close");
  });
	
	//Services for Nokia Maps 2.0 tab
	$("#services-maps-2").click(function() {
	  if($(this).hasClass("close")) {
			$(this).parent().parent().parent().find(".empty-grey-block").toggleClass("close");
			$("#maps-2-tab-container").slideToggle(400);
      
		}
		else {
			$("#maps-2-tab-container").slideToggle(400, 
		  function(){ 
		    $("#services-maps-2").parent().parent().parent().find(".empty-grey-block").toggleClass("close");
		  });
			  
		}
		$(this).toggleClass("close");
  });
	
	//Services for Nokia Maps on S40 devices tab
	$("#services-maps-s40").click(function() {
	  if($(this).hasClass("close")) {
			$(this).parent().parent().parent().find(".empty-grey-block").toggleClass("close");
			$("#maps-s40-tab-container").slideToggle(400);
      
		}
		else {
			$("#maps-s40-tab-container").slideToggle(400, 
		  function(){ 
		    $("#services-maps-s40").parent().parent().parent().find(".empty-grey-block").toggleClass("close");
		  });
			  
		}
		$(this).toggleClass("close");
  });


  /*
   * Handle #anchor linking. (including to elements that have display="none" due to dynamic tabbing:
   */
  //trigger the tab specified in the location.hash
  if ((tabLinks.hashName != '' ) && (tabLinks.hashName != '#') && (tabLinks.hashName.indexOf('#') != -1)) {
    r = $("a[href='"+tabLinks.hashName+"']").trigger("click");
    //alert("2");
  }

  //if the particular section is hidden, show it by triggering a click on the "Services for Nokia Maps version" link
  if ((tabLinks.hashName != '' ) && (tabLinks.hashName != '#')) {
    var t = $("a[href='"+tabLinks.hashName+"']").parent().parent().parent().parent();
    //debugLog("Class name of t: ");
    //debugLog(t);
    if ( $(t).hasClass('inner-tab-content') ) {
      $('.services-title .close', t).trigger("click");
      //alert("3");
    }
  }
  
  //trigger the tab containing the parent of the tab specified in the location.hash
  if ((tabLinks.hashName != '') && (tabLinks.hashName != '#') && (tabLinks.hashName.indexOf('#') != -1)) {
    r = $('#'+tabLinks.parentId+'-tab a').trigger("click");
    //alert(tabLinks.parentId+'-tab a');
    //alert("4");
  }
  if (tabLinks.parentId != undefined) {
    //scroll to the element with id=location.hash
    setTimeout(function(){scrollToElement($(tabLinks.hashName)[0]);}, 1300);
  }
  OviMapsFunctions.detectOS();
  
  //Add HBX tracking to Mac Map-loader link
  if(OviMapsFunctions.systemOS == 'mac') {
    if (typeof hbx ==  "object") {
      if (hbx.mlc != undefined) {
        var hbxMlc = hbx.mlc;
      
        var fileHbx = $("#download-loader-mac").attr('href').replace(/.*\//g, '');
        hbxMapLoaderFn = "_hbPageView('"+fileHbx+"','"+
          OviMapsFunctions.generateMlc(hbxMlc, '/map+loader/'+fileHbx)+"')";
        //add HBX event to "Download" button
        $('#download-loader-mac').click(function() {
          if (hbxMlc != false) setTimeout(hbxMapLoaderFn, 1300);
        });
      }
    }
  }

  //display map-loader element if it's included in the hash link:
  if(location.hash.indexOf("map-loader") != -1) {
    $('#map-loader').parent().parent().trigger("click");
  }
});
