/****************************************************************
 * Get browser info script.
 * created: 6-Aug-2009
 * author: Bsv
 * 
 * Tries to get information from:
 *  Navigator Object, 
 *  use ActiveXObject for IE pluggin detection, 
 *  makes calculation for connection speed
 * Has ability to send all grabbed information via default 
 * mail client
 * 
 * Input parameters:
 * 'html' - as result redrowDocument() will be called
 * 'form' - as result document.contact_form.info.value 
 *          will be populated
 * 'both' - as result - document.contact_form.info.value 
 *          will be populated AND redrowDocument() will be called
 * 
 * As result:
 *  info could be rendered on html page,
 *  could be passed to document.contact_form.info.value,
 *  could be send via default mail client
 *  
 * see methods redrowDocument()
 * and prepareInfo() 
 * 
 * Requirements:
 * 1. These div-s should be present inside html:
 * <div id="loadImage" style="position: absolute; top: -1000px; left: -1000px;" ></div>
 * <div id="content"></div>
 * <div id="loadDiv" style="font-weight:bold; color: grey; margin-top: 20px; text-align: center;">L O A D I N G ...</div>
 * 2. Body onLoad should call showInfo()
 * 
 ****************************************************************/
  
  /**
   * Obtain input parameter
   * Expects: 'html' or 'form'
   */

  var script_action = getInputParameter();

  /**
   * Map form fields names for submit validation
   */
  var m_fieldsMap = new Map();

  /**
   * Variables for speed calculating
   */ 
  var m_bps=-1;
  var m_startTime = new Date().getTime();

  var m_ip=-1;

  function get_random()
  {
    return escape( (new Date().getTime()));
  }

  /**
   * Retrievs parameter passed to scrip src 
   * <script src=contactus.js?action=[value] 
   */
   function getInputParameter()
   {
	var inParam='';
	var scripts = document.getElementsByTagName ('script');
	for (var s, i = scripts.length; i && (s = scripts[--i]);) 
	{
	    if ((s = s.getAttribute ('src')) && (s = s.match (/^(.*)contactus.js(\?\s*(.+))?\s*/))) 
	    {
	      break;
	    } 
	}

	var tmp_actions = s[3].split('=');
	inParam = tmp_actions[1];
	
	return inParam;
   }
  
  /**
   * Main mathod. It should call:
   * 1. redrawDocument() - for render info into the same page as html
   * or
   * 2. prepareInfo() - for pass info into hidden field of html form
   */
  function showInfo() 
  {
	var speedTestImg;
    var startTime = new Date().getTime();

    speedTestImg = new Image();
      
    speedTestImg.onload = function() 
    {
         var endTime = new Date().getTime();
         /* Speed in KB/s for test image opening */ 
         m_bps = 91311 / (endTime - startTime) * 1000 / 1024;

         if( script_action == 'html')
         {
         /* Used for render info into the same page */
        	 redrawDocument();
         }
         else if (script_action == 'form' )
         {
         /* Used for pass info into hidden form field */
        	 prepareInfo();
        	 initFieldsMap();

        	 /* Show message after info was sent
        	  * 1 - all right
        	  * 2 - email sent but records to db has not created
        	  * 3 - all bad, info didn't send and didn't register 
        	  * */
        	 if(getRequestParameter('res') == 1)
        	 {
        		 showOkMessage();
        	 }
        	 else if(getRequestParameter('res') == 2)
        	 {
        		 showOkMessage();
        	 }
        	 else if(getRequestParameter('res') == 3)
        	 {
        		 //TODO error message should be here
        	 }
         }
         else if (script_action == 'both' )
         {
         /* Used for pass info into hidden form field and redraw page's info */
        	 initFieldsMap();
        	 prepareInfoAndRedrowDocument();
         }
         else
         {
             document.getElementById("loadImage").style.display = 'none';
             document.getElementById("loadDiv").style.display = 'none';
        	 alert('You tried to use CONTACTUS.JS incorrectly!');
         }
    }

    speedTestImg.src = "img/wedding.JPG?t="+ get_random();
    document.getElementById("loadImage").appendChild(speedTestImg);

  }

  /**
   * Obtains Flash plugin version under IE
   */
  function getVersionIfFlashExistUnderIE()
  {
	var version=-1;

	if (navigator.userAgent.indexOf('MSIE') == -1)
	{
		return version;
	}

	try 
	{
			var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = axo.GetVariable("$version");
	} 
	catch (e){}
		  
	return version;
  }
  
  /**
   * Obtains IE plugins.
   * Could be extended for add another plugins 
   */
  function getIEplugins()
  {
	var ie_plugins='';
	var statusStr='';	

	if (navigator.userAgent.indexOf('MSIE') == -1)
	{
		return 'Not defined';
	}
	
	var vers=getVersionIfFlashExistUnderIE();
	
	/**
	 * Flash Detection for IE
	 */
	 if( vers != -1 )
	 {
	 	ie_plugins += 'ShockwaveFlash - ';
	 	ie_plugins += vers;
	 	ie_plugins += '<br>';
	 }

  	/**
	 * Java Detection for IE
	 */
	try 
	{
		new ActiveXObject("JavaPlugin");
		ie_plugins += 'Java Plug-in : [ENABLED] ';
		ie_plugins += '<br>';
  	} 
  	catch (e)
  	{
  		statusStr += e.message;
  	}

  	/**
  	 * AJAX detection
	 */
	try
  	{
		new ActiveXObject("Microsoft.XMLHTTP");
		ie_plugins += 'AJAX : [SUPPORTED]';
		ie_plugins += '<br>';
	}
  	catch (e)
  	{
	  		statusStr += e.message;
  	}  	 	

  	/**
  	 * Skype detection
  	 */
	try 
  	{
		new ActiveXObject("Skype.Detection");
		ie_plugins += 'Skype : [INSTALLED] ';
		ie_plugins += '<br>';
	} 
  	catch (e)
  	{
  		statusStr += e.message;
  	}

  	/**
	 * Skype IE plug-in detection
	 */
	try 
	{
		/**
		 * Lived for experiments !!!
		 *
			new ActiveXObject("FSFilter Activity Monitor");
			ie_plugins += 'Skype Plug-in : [INSTALLED] ';
			ie_plugins += '<br>';
		 */

	} 
	catch (e)
	{
		statusStr += 'Ooops! ...';
		statusStr += e.message;
	}

	window.status = statusStr;

	return ie_plugins;
  }

  /**
   * Obtains IE mime types
   * Default implementation. Could be investigated for improve
   */
  function getIEmimeTypes()
  {
	var ie_mimetypes='';

	if( (navigator.mimeTypes && navigator.mimeTypes.length > 0) ) 
	{
		ie_mimetypes += 'Registered mime-types : ';
		ie_mimetypes += navigator.mimeTypes.length
	}
	else
	{
		ie_mimetypes +='Not detected';
	}

  	return ie_mimetypes;

  }
  
  /**
   * Obtain mime types from Navigator Object
   * returns html rows table with following columns : number-type-description-plugin.name-suffixes 
   */
  function getMimeTypes()
  {
	var mimetypes='';
		
	if ((navigator.userAgent.indexOf('MSIE') != -1) && (navigator.userAgent.indexOf('Win') != -1))
	{
		mimetypes=getIEmimeTypes();
	}
	else
	{
		if( (navigator.mimeTypes && navigator.mimeTypes.length > 0) ) 
		{
	  		var i=0;
      		var count=1;

			for(var i=0; i<navigator.mimeTypes.length; i++)
      		{
				if(mimetypes.indexOf(navigator.mimeTypes[i].type) == -1)
          		{
           			mimetypes +='<tr>';
           			mimetypes += '<td width=10% align="center">';
           			mimetypes += count;
           			mimetypes += '</td><td width=20%>';
           			mimetypes += navigator.mimeTypes[i].type;
           			mimetypes += '</td><td width=30%>[';
           			mimetypes += navigator.mimeTypes[i].description;
           			mimetypes += ']</td><td width=20%>[';
					try
					{
           				mimetypes += navigator.mimeTypes[i].enabledPlugin.name;
					} 
					catch(e) 
					{
						mimetypes += 'Not defined';
					}
           			mimetypes += ']</td><td width=20%>[';
					try
					{
	           			mimetypes += navigator.mimeTypes[i].suffixes.replace(/,/g," ");
					}
					catch(e) 
					{
							mimetypes += 'Not defined';
					}
           			mimetypes += ']</td>';
           			mimetypes +='</tr>';
           			count++;
          		}
       		}
     	}
		else
		{
			mimetypes='Not detected';
		}
	}
		return mimetypes;
  }	

  /*
   * Obtains plugins from Navigator Object.
   * Returns String with following format: [number]-name-description<br>
   */
  function getPlugins()
  {
    var plugins='';

    if ((navigator.userAgent.indexOf('MSIE') != -1) && (navigator.userAgent.indexOf('Win') != -1)) 
	{
	  plugins = getIEplugins();	
	}	 
	else
	{
		if( (navigator.plugins && navigator.plugins.length > 0) ) 
     	{
	  		var i=0;
      		var count=1;

			for(var i=0; i<navigator.plugins.length; i++)
      		{
          		if(plugins.indexOf(navigator.plugins[i].name) == -1)
          		{
           			if(i != 0)
            			plugins+='<br>';
           			plugins +='['+(count)+']-';
   	       			plugins += navigator.plugins[i].name;
           			plugins +='-[';
   	       			plugins += navigator.plugins[i].description;
           			plugins +=']';
           			count++;
          		}
       		}
       
     	}
    	else
    	{
      		plugins = 'Not detected';
    	}
	}

	return plugins;
  }

  /**
   * Redraw page
   */
  function redrawDocument()
  {
      document.getElementById("loadImage").style.display = 'none';
      document.getElementById("loadDiv").style.display = 'none';
      document.getElementById("content").innerHTML = renderDocument(); 
      return true;
  }

  /**
   * Pass info into hidden field
   */
  function prepareInfo()
  {
      document.getElementById("loadImage").style.display = 'none';
      document.getElementById("loadDiv").style.display = 'none';
      document.contact_form.info.value = renderInfo();
  }
  
  /**
   * Pass info into hidden field and Show info on the page as well
   */
  function prepareInfoAndRedrowDocument()
  {
      document.getElementById("loadImage").style.display = 'none';
      document.getElementById("loadDiv").style.display = 'none';
      document.contact_form.info.value = renderInfo();
      document.getElementById("content").innerHTML = renderDocument(); 
  }

  
  /**
   * Build body for troubleshooting email
   */
  function getBody()
  {
	var body = '[[ BROWSER INFO: ]]%0A%0AConnectionSpeed='+parseInt(m_bps)+'KB/sec%0A%0A';
	var count =1;
	var propCount=0;
	
	for (var prop in navigator)
	{
		if(typeof(navigator[prop]) == 'boolean')
			break;		
		body +=prop;
		body +='=';
		body +=navigator[prop];
		body +='%0A%0A';
		propCount++;
	}   

	if(propCount == 0)
	{
		body +='userAgent=';
		body +=	navigator.userAgent;
		body +='%0A%0A';
	}
	
	/**
	 * Check flash version for troubleshooting email
	 */
	body += 'Flash='

	if ((navigator.userAgent.indexOf('MSIE') != -1) && (navigator.userAgent.indexOf('Win') != -1)) 
	{
		var flashversion=getVersionIfFlashExistUnderIE();
		if(getVersionIfFlashExistUnderIE() == -1)
		{
			body += 'Not detected';
		}
		else
		{
			body += flashversion;
		}
	}
	else
	{
		body += navigator.plugins['Shockwave Flash'].description;
	}	
	body += '%0A%0A';
	
	body += '[[ DISPLAY INFO: ]]%0A%0A';	
	body += 'Width='+window.screen.width+'%0A%0A';
	body += 'WidthAvail='+window.screen.availWidth+'%0A%0A';
	body += 'Height='+window.screen.height+'%0A%0A';
	body += 'HeightAvail='+window.screen.availHeight+'%0A%0A';
	body += 'ColorDepth='+window.screen.colorDepth+'%0A%0A';
	body += 'PixelDepth='+window.screen.pixelDepth+'%0A%0A';

	
	body += '[[ MIME_TYPES: ]]%0A%0A';	

	if ((navigator.userAgent.indexOf('MSIE') != -1) && (navigator.userAgent.indexOf('Win') != -1)) 
	{
		body +='Not Defined%0A%0A';
	}	 
	else
	{

		for (var i=0; i<navigator.mimeTypes.length; i++)
		{
			if(body.indexOf(navigator.mimeTypes[i].type) == -1)
      		{
				if(body.indexOf('application/x-java') != -1)
					break;
				if(body.indexOf('QuickTime Plug-in') != -1)
					break;
				body += '[' + count + ']-';
       			body += navigator.mimeTypes[i].type;
       			body += "--";
       			body += navigator.mimeTypes[i].description;
       			body += "--";
				try
				{
       				body += navigator.mimeTypes[i].enabledPlugin.name;
				} 
				catch(e) 
				{
					body += 'Not defined';
				}
				body +='%0A%0A';
				count++;
      		}
		}   
	}

    body=body.replace(/ /g,"_");
  
	return body;
  }

  function renderInfo()
  {
	  /**
	   *  Variables for reports tables
	   */
	  var tableWidth = 650;
	  var tableBGcolor= '#ffffe0';

	  var info= '<center><h2>Browser info</h2><table width='+tableWidth+' border=1 bgcolor='+tableBGcolor+' >' +
		'<tr><td>AppCodeName</td><td>'+navigator.appCodeName+'</td></tr>' +
		'<tr><td>AppMinorVersion</td><td>'+navigator.appMinorVersion+'</td></tr>' +
		'<tr><td>AppName</td><td>'+navigator.appName+'</td></tr>' +
		'<tr><td>AppVersion</td><td>'+navigator.appVersion+'</td></tr>' +
		'<tr><td>CpuClass</td><td>'+navigator.cpuClass+'</td></tr>' +
		'<tr><td valign=top>MimeTypes:</td><td>'+getIEmimeTypes()+'</td></tr>' +
		'<tr><td>onLine</td><td>'+navigator.onLine+'</td></tr>' +
		'<tr><td>OpsProfile</td><td>'+navigator.opsProfile+'</td></tr>' +
		'<tr><td>Platform</td><td>'+navigator.platform+'</td></tr>' +
		'<tr><td>SystemLanguage</td><td>'+navigator.systemLanguage+'</td></tr>' +
		'<tr><td>UserAgent</td><td>'+navigator.userAgent+'</td></tr>' +
		'<tr><td>UserLanguage</td><td>'+navigator.userLanguage+'</td></tr>' +
		'<tr><td>UserProfile</td><td>'+navigator.userProfile+'</td></tr>' +
		'<tr><td>Connection speed</td><td>'+parseInt(m_bps)+' KB/sec</td></tr>' +
	        '</table></center><br><center><h2>Browser security</h2><table width='+tableWidth+' border=1 bgcolor='+tableBGcolor+' >' +
		'<tr><td>CookieEnabled</td><td>'+navigator.cookieEnabled+'</td></tr>' +
		'<tr><td>Java Script Enabled</td><td>'+navigator.javaEnabled()+'</td></tr>' +
		'<tr><td valign=top>Plugins:</td><td>'+getPlugins()+'</td></tr>' +
	        '</table></center><br><center><h2>Display info</h2><table width='+tableWidth+' border=1 bgcolor='+tableBGcolor+' >' +
		'<tr><td>Width</td><td>'+window.screen.width+'</td></tr>' +
		'<tr><td>WidthAvail</td><td>'+window.screen.availWidth+'</td></tr>' +
		'<tr><td>Height</td><td>'+window.screen.height+'</td></tr>' +
		'<tr><td>HeightAvail</td><td>'+window.screen.availHeight+'</td></tr>' +
		'<tr><td>colorDepth</td><td>'+window.screen.colorDepth+'</td></tr>' +
		'<tr><td>pixelDepth</td><td>'+window.screen.pixelDepth+'</td></tr>' +
        '</table></center>';
		if((navigator.mimeTypes && navigator.mimeTypes.length > 0))
		{
			info += '<br><center><h2>Mime types</h2><table width='+tableWidth+' border=1 bgcolor='+tableBGcolor+' >' +
				  	'<tr><td align="center"><b>n/n</b></td><td align="center"><b>Type</b></td><td align="center"><b>Description</b></td><td align="center"><b>Plugin Name</b></td><td align="center"><b>Suffixes</b></td></tr>' +getMimeTypes() +
			        '</table></center>';
		}
	  
	  return info;
  }
  
  /**
   * ThePlace where info document builds
   */
  function renderDocument()
  {
	  var mailto = 'Please click this link <a href=mailto:membersupportqa@panraven.com?subject=Panraven%20Troubleshooting&body=' + getBody()+ 
		'><b>to send the information</b></a> below<br> to Panraven Member Support via your email client<br>';

	  /* for add ability to send email via email client of user use 'var content = mailto + renderInfo();' instead of line below */ 
	  var content = renderInfo();

      return content;
  }

 /**
  * Check if required fields have been filled
  */
 function check(recFields)
 {
  var count=0;

  var recFieldsArray = recFields.split(",");

  for(var i=0; i< recFieldsArray.length; i++)
  {
	if( document.contact_form[recFieldsArray[i]].value == '' )
	{
		alert('Field ['+m_fieldsMap.get(recFieldsArray[i])+'] can not be empty. Please fill it and press [Submit] again.');
		count++;
		break;
	}
  }

  if(count == 0)
  {
   document.contact_form.submit();
  }

 }

  /**
   * Init map for check fields after submit
   */
   
   function initFieldsMap()
   {
    m_fieldsMap.put(document.contact_form['name'].name,'First Name');
    m_fieldsMap.put(document.contact_form['field-a9b930ffb697186'].name,'Last Name');
    m_fieldsMap.put(document.contact_form['email'].name,'EMAIL');
    try
    {
    	m_fieldsMap.put(document.contact_form['field-79adf86b4e0edab'].name,'Display Name');
    	m_fieldsMap.put(document.contact_form['field-9f7d93d89ea06ce'].name,'Reason for your inquiry');
    	m_fieldsMap.put(document.contact_form['field-0a77435578e0b0e'].name,'Question or issue in detail');
    }
    catch(e){}
   }

   /**
    * Get request parameters
    */
   function getRequestParameter ( param )
   {
	var q = document.location.search || document.location.hash;

	if (param == null) 
	{ 
		return q; 
	}

	if(q) 
	{
		var pairs = q.substring(1).split("&");
		for (var i=0; i < pairs.length; i++) 
		{
			if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) 
			{
               var value = pairs[i].substring((pairs[i].indexOf("=")+1));
               return decodeURI(value);
			}
		}
	}
	return "";
   }

   /**
    * Show message bubble
    */
    function showOkMessage()
    {
		 document.getElementById('border4').style.display = '';
		 document.getElementById('messageSentBubble').style.display = '';
		 document.getElementById('aboutus_wrapper').style.display = 'none';
		 document.getElementById('accessKeyValue').innerHTML = " "+getRequestParameter("accessKey");

    }
    
    /**
     * Hide message bubble
     */
     function hideOkMessage()
     {
		 document.getElementById('border4').style.display = 'none';
		 document.getElementById('messageSentBubble').style.display = 'none';
		 document.getElementById('aboutus_wrapper').style.display = '';
		 document.getElementById('accessKeyValue').innerHTML = '';
     }
