/*
 * String comparison utility function
 ****/
function strComp(str1, str2) {
  if ( str1 > str2) return 1;
	if ( str1 < str2) return -1;
	else return 0;
}

/*
 * Device list sort function
 * Puts E-devices first, N-devices next, Numerical devices last
 ****/

function deviceSort( el1, el2 ) {
	//get device name from device items
	a = $(el1).find('phone_id_txt').text();
	b = $(el2).find('phone_id_txt').text();

	if(a.indexOf("Nokia N") != -1 && b.indexOf("Nokia N") != -1) 
		return -strComp(a, b);
	if(a.indexOf("Nokia E") != -1 && b.indexOf("Nokia E") != -1) 
		return -strComp(a, b);
	if(a.indexOf("Nokia E") != -1 && b.indexOf("Nokia N") != -1) 
		return strComp(a, b);
	if(b.indexOf("Nokia E") != -1 && a.indexOf("Nokia N") != -1) 
		return strComp(a, b);
	return -strComp(a, b);
}


/*
 * Container holding dynamic functionality for Nokia Maps feature pages
 ****/
var FeaturePages = {
  //currently active device
  device : '',
  //counter used to generate HTML for feature-rows
  featureCount : 0,

	//global field holding the number of the related features associated with currently viewed feature
	//used at least by showRelatedFeatures and addFeatureHTML
	featuresTotal : -1,
  

	/* Complete device list */
  generateDeviceList : function() {
		//sort devices
    //go through all devices
		var deviceArray = [];
		$('array#models > item', XMLData.devices).each(function(){
			deviceArray.push($(this));
		});
		deviceArray.sort(deviceSort);

		//gps icons
		gpsIconYes = $('item#general gps_icon', XMLData.devices).text();
		gpsIconNo = $('item#general no_gps_icon', XMLData.devices).text();

		//gps texts
		gpsTxtYes = $('item#general gps_txt', XMLData.devices).text();
		gpsTxtNo = $('item#general no_gps_txt', XMLData.devices).text();



		$.each(deviceArray, function() {
      // software version code
      var version = $(this).find('maps_version').text();
      // phone image location
      var img = $(this).find('image').text();
			
			gpsNo = $('no_gps', this).text();
			if(!(gpsNo == 'true') ) {
				gpsHTML = '<span class="gpsTxt green">' + gpsTxtYes + '</span>';
				//gpsHTML = '<img class="gpsIcon" src="'+gpsIconYes+'" />'; 
			} else {
				gpsHTML = '<span class="gpsTxt grey">' + gpsTxtNo + '</span>';
				//gpsHTML = '<img class="gpsIcon" src="'+gpsIconNo+'" />'; 
			}
			
			// device name
      var device = $(this).find('phone_id_txt').text();
      
      var imgHTML = '<img class="phoneImg" src="'+img+'" />';
      var txtHTML = '<span class="captionPhone">'+device+'</span>';
      var deviceHTML = '<div class="phoneContainer">' +
                         '<div class="selectPhone" onclick="FeaturePages.showDeviceFeatures(\''+version+'\',\''+device+'\')">' +
                           imgHTML + txtHTML + gpsHTML
                         '</div>' +
                       '</div>';
      
      $(deviceHTML).appendTo('#device_selector');
    });
    
    //device hover effects
    $('.selectPhone').hover(
      function() {
        $(this).addClass('selectPhoneHover');
        //$('.captionPhone', this).addClass('captionPhoneHover');
        //$('.gpsTxt', this).addClass('gpsTxtHover');
      },
      function() {
        $(this).removeClass('selectPhoneHover');
        //$('.captionPhone', this).removeClass('captionPhoneHover');
        //$('.gpsTxt', this).removeClass('gpsTxtHover');
      }
    );
  },
	
	/* Complete feature list */
  generateFeatureList : function() {
    //go through all features
		FeaturePages.featuresTotal = $('feature', XMLData.features).length - 1;
    $(XMLData.features).find('feature').each(FeaturePages.addFeatureHTML);
		FeaturePages.featureTotal = -1;
  },

  /*
   * Show related features based on feature ID
   * used in the stand-alone feature pages as 
   * optional dynamic content
   ****/
  showRelatedFeatures : function(id) {
		//reset the feature counter
		FeaturePages.featureCount = 0;
		$('#related_features')[0].style.visibility = "visible";
    //comma separated feature list
    f = $('feature#'+id+' related', XMLData.features).text();
    //feature array
    fa = f.split(',');
    
		//set global variable holding the length of the feature array
		FeaturePages.featuresTotal = fa.length - 1;

    $('#features_container').empty();
    

    //go through feature IDs inside fa and print all features for the software version
    for(i in fa) {
			$(XMLData.features).find('feature#'+fa[i]).each(FeaturePages.addFeatureHTML);
    }
		
		//reset the number of related features
		FeaturePages.featuresTotal = -1;
  },

  updateScrollPane : function() {
    $('#device_selector').jScrollPane({
      dragMinHeight: "42", 
      dragMaxHeight: "300",
      showArrows: true
    });
  },

  showDeviceSelector : function() {
    //initiliaze the scrollpane
    $('#device_selector_container').show();
		$('#device_selector_head').hide();
    
    try {
			FeaturePages.updateScrollPane();
	  } catch(e) {}
  
    //$('#device_selector').jScrollPane();
    //show the Scrollpane
    $('#device_selector').parent().show();
    $('#device_info').hide();
		this.removeDeviceFilter();
		$('#device_filter').val('');		
  },
  
  hideDeviceSelector : function() {
		$('#device_selector_head').show();
		$('#device_selector_container').hide();
	},

  /*
   * Handle filtering device list based on user input
   */ 
  filterDevice : function() {
    //get user input
    q = $('#device_filter').val().toLowerCase();

    if (q.length == 1) {
      FeaturePages.removeDeviceFilter();
    }

    $('.phoneContainer').each(function() {
      //get the device name
      caption = $('.captionPhone', this).text().toLowerCase();
      if(caption.indexOf(q) != -1) { 
        $(this).show();
      } else {
        $(this).hide();
      }
    });

    FeaturePages.updateScrollPane();
  },

  /*
   * Remove possible device filtering 
   */
  removeDeviceFilter : function() {                 
    $('.phoneContainer').each(function() {       
      $(this).show();    
    });
    $('#device_fitler').val('');
  },

  /* Callback function used to extract individual feature XML and generate HTML out of it */
  addFeatureHTML : function(count) {
    name = $(this).find('name').text();
    img = $(this).find('icon').text();
    desc = $(this).find('desc').text();
    link = $(this).find('link').text();
    linkText = $(this).find('linktext').text();

		//fetch tag data
		tagId = $(this).find('tag_id').text();
		tagData = $('tagdata tag#'+tagId, XMLData.features);
		tagText = $('text', tagData).text();
		tagColor = $('color', tagData).text();
		tagIcon = $('icon', tagData).text();
    tagTooltip = $('tooltip', tagData).text();
    //tagTooltip = '<div style=\'float: left;\'>'+tagTooltip+'</div>';
		//tag-specific HTML code
		tagHTML = '';
		
		//if valid tag is specified, generate HTML for displaying the tag
		if (tagData.length == 1) {
		  tagHTML = '<div class="featureTag" onmouseover="Tip(\''+tagTooltip +'\')" onmouseout="UnTip()">'+
                '<img src="'+tagIcon+'" />' +
			          '<span style="color: '+tagColor+';">'+ tagText + '</span>' +
      			    '</div>';
		}

    //append device-specific URL parameter to the link going to specific feature page
    /*if(FeaturePages.device !== '') {
      link+= '?device='+FeaturePages.device;
    }*/
		
    //columnClass is a CSS class name for the feature column 
    //Can be left or right depending on whether count is odd or even

    //check if the feature number is odd or even, 
    //and create feature-rows accordingly
    if(FeaturePages.featureCount%2 == 0) {
			if ( FeaturePages.featureCount == FeaturePages.featuresTotal && 
			     FeaturePages.featuresTotal != -1 && 
					 FeaturePages.featuresTotal%2 == 0) {
				featureRowHTML = '<div class="featureRowOdd">';
			} else {
	      featureRowHTML = '<div class="featureRow">';
		  }
      columnClass = 'leftColumn'; 
    } else {
      columnClass = '';
    }
   	 
    featureRowHTML += '<div class="featureColumn '+columnClass+'">' + tagHTML +
                    '<div class="featureIcon">' +
                      '<img src="'+img+'" />' +
                    '</div>' +
                    '<div class="featureText">' +
                      '<p><a href="' + link + '" class="featureLinkTop">' + name + '</a><br />' + desc + 
											'<a href="' + link + '" class="featureLinkBottom">'+linkText+'</a></p>'+
 								   '</div></div>';
    
    //always append 2 features at a time, unless the current feature is the last one
    if ( FeaturePages.featureCount%2 == 1 
				 || FeaturePages.featuresTotal == FeaturePages.featureCount ) {
      featureRowHTML += '<div class="featureRowBottom"></div></div>';
      $(featureRowHTML).appendTo('#features_container');
    } else {
		}
    FeaturePages.featureCount++; 
  }, 
  
  //Repopulates and shows the device info box and hides the device selector
  showDeviceInfo : function(device) {
    // find xml section with device = device
    $('item:has(phone_id_txt:contains('+device+'))', XMLData.devices).
			 filter(function() { return $('phone_id_txt', this).text() == device; }).each(function() {
      image = $('image', this).text();

			version = $('maps_version', this).text();
			noGPS = $('no_gps', this).text();
			if ( noGPS != "true" ) {
				desc = $('item#featuredata '+version+' text_gps', XMLData.devices).text();
			} else {
			  desc = $('item#featuredata '+version+' text_no_gps', XMLData.devices).text();
			}
			desc = desc.replace(/\$phone/, device);
			
				
      //productpage = $('productpage', this).text();
			//get software version text 
			swTxtTag = $('software_txt', this).text();
			swVersionTxt = $('item#macros '+swTxtTag, XMLData.devices).text();

			//download location
			dlID = $('download_url', this).text();
			dlURL = $('item#macros > item#' + dlID + ' > url', XMLData.devices).text();
			dlPopup = $('item#macros > item#' + dlID + ' > popup', XMLData.devices).text();

			//set the the download location to either a JavaScript pop-up or a new page
			//by setting the download link's attributes
			if(dlPopup == "false") {
			  dlAttr = { href: dlURL, target: '_blank' };
			} else {
			  dlAttr = { href: "javascript:window.open('" + dlURL + "',"+
								         "'legal','left=20,top=20,width=510,height=525,toolbar=0,resizable=1');" +
												 "void(0);",
							    target: "_self" };
			}
     
      $('#device_info .staticPhone img').attr({ src : image });
			$('#device_info .staticPhone span').text(swVersionTxt);
			heading = $('uidata > text > deviceheading', XMLData.features).text().
				replace(/\$phone/, device);
      $('#device_info h3').text(heading);
      $('#device_info .descPhone p')[0].innerHTML = desc;
      //$('#productPageLink a').attr({ href : productpage });
			$('#downloadSoftwareLink a').attr(dlAttr);
    });
		$('#device_selector_head').hide();
    $('#device_selector_container').hide();
    $('#device_info').show();
  },

  //Displays device-specific features
  showDeviceFeatures : function(ver, device) {
		//exception for s40 devices
		if ( ver == 's40_1' ) {
			url = $('page_locations > s40_features', XMLData.features).text();
			location = url + '?device='+device;
			return;
		} else if ( ver == 's60_1' ) {
			url = $('page_locations > maps_1_features', XMLData.features).text();
			location = url + '?device='+device;
			return;
		} else {
			location.hash='#device='+device;
		}
    FeaturePages.device = device;
    FeaturePages.featureCount = 0;
    
    //comma separated feature list
    f = $('featuremap software#'+ver, XMLData.features).text();
    //feature array
    fa = f.split(',');
    
    $('#features_container').empty();

    //go through feature IDs inside fa and print all features for the software version
    for(i in fa) {
      $(XMLData.features).find('feature#'+fa[i]).each(FeaturePages.addFeatureHTML);
    }

    //Show the device specific box and hide the device list
    this.showDeviceInfo(device); 
    
  },
  
  //Displays default feature list
  showAllFeatures : function() {
	  //clear the URL hash params
		location.hash =  '#';
    $('#features_container').empty();
    FeaturePages.featureCount = 0;
    //we are appending HTML for 2 features (feature row) at the time
    this.featureRowHTML = '';
    
    //go through all features
    FeaturePages.generateFeatureList();
    //$('features', XMLData.features).find('feature').each(FeaturePages.addFeatureHTML);
    this.featureCount = 0;
    this.showDeviceSelector();

  },

  /* Generate screenshot navigation toolbar
   * requires that <img class="scr" ... /> HTML elements containing screenshots are present
	 * Takes the ID of the container DIV as an argument
   ****/
	generateScreenshotNavi : function(parentDivId) {
		//number of screenshots in the container (images of class="scr")
		nScr = $('#'+parentDivId+' .scr').length;
		
		//don't show navi if one or less screenshots are present
		if (nScr <= 1) {
			 return;
		}
		
		//navi graphics
		g = $('featuredata > uidata > graphics', XMLData.features);
		navLeft = $('scrnavi_left', g).text();
		navRight = $('scrnavi_right', g).text();
		navActive = $('scrnavi_active', g).text();
		navInactive = $('scrnavi_inactive', g).text();

		//HTML code for the screenshot navi container and UI
		scrNaviHTML = '<div class="scrNaviOuter"><div class="scrNaviWrap">'+
									'<ul><li><img src="' + navLeft + '" /></li>';
		for(i = 0; i < nScr; i++) {
			if(i == 0) {
				 attr = 'src="' + navActive + '" selected="true" nr="0"';
			} else {
				 attr = 'src="'+ navInactive +'" selected="false" nr="'+ i +'"';
			}
			scrNaviHTML += '<li><img class="scrNaviButton" ' + attr + '/><li>';
		}
		scrNaviHTML += '<li><img src="'+ navRight +'" /></li></ul></div></div>';
		
		//parentDivId = id of the screenshot containing box
		$(scrNaviHTML).appendTo('#'+parentDivId);

	 
		//screenshotnavi events
		$('#'+parentDivId +' .scrNaviButton').hover(
			function() {
				$(this).attr({ src: navActive });
			},
			function() {
				if($(this).attr('selected') == "false")
					$(this).attr({ src: navInactive });
			} 
		);

		$('#'+parentDivId +' .scrNaviButton').click(
			function() {
				$('#'+parentDivId+' .scr').css({ visibility: 'hidden' });
				var nr = $(this).attr("nr");
				$('#'+parentDivId +' .scr')[nr].style.visibility = "visible";
				$('#'+parentDivId +' .scrNaviButton').attr({ src: navInactive, selected: "false" });
				$(this).attr({ src: navActive, selected: "true" });
			}
		);
	}
}

