/*
   These are functions necessary for getting the Logitech Device Detection
   working. Origionally, these were included into the HTML document Logitech
   provided. I wanted to make them avaliable outside of that document, so 
   I could use them in our page. 

   The global variables are referenced throughout the HTML document and different JavaScript functions. 

   Brian J. Stinar
   1/19/2009 
*/

var isIE = ( navigator.product != 'Gecko' );
var isIE64 = ( isIE == true ) && ( navigator.appVersion.indexOf( 'x64' ) != -1 || navigator.appVersion.indexOf( 'Win64' ) != -1 );
var oProperties = null;
var foundCTIDs = new Array();
var showingNew = true;  // Are we using the new mechanism to show things? 
var success = false; // Have we succeeded?   
var showingColor = false; // Are we showing the color selector drop-down? 
var clicked_install_message = false; // Did we display the installation message? TODO: BJS 2/4/2010 - use a different div for this

// This already broke once when they changed their product description path (1-25-2010)
var usingLeaderTech = false; 
var requests = 0; // Used for asynchrously grabbing data

function nothing(){}

function zeroProductAndSubmit(){
   document.forms.regform.PAGE.value = 'Index';
   document.forms.regform.WHPR.value = '';
   document.forms.regform.PCAT.value = '';
   document.forms.regform.WHFM.value = '';
   document.forms.regform.HWPD.value = '';     

   document.forms.regform.submit();
}


function tryComponent(){
   var ddc = document.getElementById('LogitechDDC');
   // see if we can access the method on the component
   try{
      ddc.SysVer();
      // if we can, hide the installation instructions
      document.getElementById('installation_instructions').style.display = "none";
      document.getElementById('spinner').style.display = "none"; 
      document.getElementById('image_spinner').style.display = "none";
      StartDetection();
   }
   catch(e){
      // I only really want to do this on the reload that I can control...
      // So, if the page reloads once, I need to be able to measure that, 
      // then, if the page has reloaded once,
      // I want to try and reload it a second time, after waiting a second for the 
      // installation messaging to take the focus.
      setTimeout(retry, 500); 
   }

}

function retry(){
   var ddc = document.getElementById('LogitechDDC');
   if (ddc.object != null){
      window.onbeforeunload = function () {}; // Let's see if this clears the browsers cache, avoiding the prompt for form resubmittal. 
      window.location.reload();
   }
   setTimeout(retry, 500); 
}

function refreshPage(){
   document.getElementById('PAGE').value = 'ProductDetection';
   document.forms.selected.submit();
}


// This is a method to grab the JSON (or any other) file that I will need asynchronously. 
// This is defined in the main page, but I need it in my ancillary page. 
function submitToLT(postURL,callback)
{   
  var xmlhttp;
    
  if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    xmlhttp = new XMLHttpRequest();
  } else if (window.ActiveXObject) { // IE
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  } 
  else
  {
    alert("Browser too old. Page won't work...");
    return;
  }

  requests++;

  async=false;
    
  xmlhttp.open( "GET", postURL, async);

  if(async)
    xmlhttp.onreadystatechange = function(e){
      if ( xmlhttp.readyState==4 ) {
        if(xmlhttp.status==200 || xmlhttp.status==null)
        {
            if(callback != null)
                callback();
        }
      }
    };

  xmlhttp.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
  xmlhttp.send( null );

  if(! async)
  {
    if(xmlhttp.status==200 || xmlhttp.status==null)
    {
        if(callback != null)
            callback(xmlhttp);
    }
  }

}

function submitValues(pcat, whfm, whpr){
   document.forms.selected.PCAT.value = pcat; 
   document.forms.selected.WHFM.value = whfm; 
   document.forms.selected.WHPR.value = whpr;
   document.forms.selected.submit();   
}

// Also used for non-ActiveX functionality
function readCookie(name) {
   var nameEQ = name + "=";
   var ca = document.cookie.split(';');
   for(var i=0;i < ca.length;i++) {
      var c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
         if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
      }
      return null;
}

// Used to close the "What is auto detect?" pop-up box 
function closeBox(){
      if (document.getElementById('explanation_holder').style.display != 'none'){
         document.getElementById('CTRY').style.visibility = 'visible';
      }
      document.getElementById('explanation_holder').style.display = 'none';
      document.getElementById('click_catcher').style.display = 'none';
}

// This function is not currently being used with the new architecture. 
// If you want to embed the ActiveX component in a web page, after the 
// page has been loaded, this is the method to use.
function conditionallyGenerateHTML(){
   // TODO: This needs to set a flag somewhere if it has been run before. 
   //       If it has been run before, and it is run again, it is going 
   //       to just keep adding stuff to the namespace. 
   //       I think the object will be over-written, since it has the same name,
   //       but I am not sure how JavaScript name conflicts are resolved and it 
   //       would be better to do this cleanly. 

   if ( isIE == false ) {
      var mimetype = navigator.mimeTypes["application/logitech-ddc-plugin"];
      if ( mimetype ){
         if ( mimetype.enabledPlugin ){

            // This was being done at page-load, I would rather have the user prompted for ActiveX installation 
            // when they click the button
            //document.writeln("<OBJECT ID='LogitechDDC' type='application/logitech-ddc-plugin' hidden='true'></OBJECT>");
            var myElement = document.createElement("<OBJECT ID='LogitechDDC' type='application/logitech-ddc-plugin' hidden='true'></OBJECT>");
            document.body.appendChild(myElement); 

            var ddc = document.getElementById("LogitechDDC");
            if ( ddc != null ){
               ddc.addEventListener('OnDetectDevicesCancelled', DetectDevicesCancelled, false);
               ddc.addEventListener('OnDetectDevicesFinished', DetectDevicesFinished, false);
               ddc.addEventListener('OnError', ErrorEncountered, false );
            }
         }
      }
   } // end if (isIE == false)
   else {
      var bitness = 32;
      if ( isIE64 == true ){
         bitness = 64;
      }
      
        if (usingLeaderTech == true){
           var plugpath = "http://wwwtest.onlineregister.com/logitechreg/plugins/LogitechDeviceDetection" + bitness + ".cab"; 
        }
        else{
           var plugpath = "http://www.logitech.com/devicedetector/plugins/LogitechDeviceDetection" + bitness + ".cab";      
        }

      // I want this element to only be added to the DOM when the user needs it 
      var myElement = document.createElement("<OBJECT ID='LogitechDDC'  CODEBASE='" + plugpath + DDCocxVersion + "' CLASSID='CLSID:0067DBFC-A752-458C-AE6E-B9C7E63D4824'></OBJECT>");
      document.appendChild(myElement);
   }
 
// This is where Xavier's install messaging needs to go
setTimeout(detectComponent, 200); 
}


// This is the method used to start the detection routines.
// It is only used in the above (unused) conditionallyGenerateHTML.
// I think this is a good example of how to detect a conditionally installed
// component, so I am leaving it in. 
function detectComponent(){
   //Only do this if the object is not available
    try{
      // Try to access a method of the object
      document.LogitechDDC.SysVer();   
   }
   catch(e)
   {
      clicked_install_message = true;

      // There was a hiccup on the SECOND instance of running the component, and the install messaging was displayed. This eliminates that. 
      if (success == true){
         return; 
      }

      // Hide the drop-down elements (ithink) that shine through in IE6
      document.getElementById("CTRY").style.visibility="hidden";
      document.getElementById("DQ07").style.visibility="hidden";
      document.getElementById("_PCATWHFM").style.visibility="hidden";
      document.getElementById("WHPR").style.visibility="hidden";


      // if we cannot access the component's method (since it is not present), do the below 
      var html_string = "<h3 class='install_heading'> Auto-detect Results</h3>\n"
      html_string += "<span class='install_text_proper'>Logitech Device Detection component is not yet installed. </span><br><br>\n";
      html_string += "<h3 class='install_heading'>What do I do now?</h3>\n";
      html_string += "<span class='install_text_proper'>This page is currently attempting to install the Device Detection control for Microsoft Internet Explorer. Depending on your browser and security settings, the following can happen: </span><br><br>\n";
      html_string += "<h3 class='install_heading' >Yellow bar at the top of the page: </h3><br>\n";
      html_string += "<span class='install_text_proper'>If Internet Explorer displays a message (seen below) above the webpage, click it to proceed with the installation.</span><br><br>\n "
      html_string += "<img width='95%' src='images/vista_install_at_top_EN.png'></img><br>\n";
      html_string += "<br><br><br><h3 class='install_heading'>Windows Vista or Windows 7 UAC warning dialog with Internet Explorer 7:</h3>\n";
      html_string += "<span class='install_text_proper'>If Windows displays the User Account Control Warning window like below, click the 'Continue' button to proceed with the installation.</span><br>\n"; 
      html_string += "<img src='images/vista_install_UAC_EN.png'></img><br>\n";
      html_string += "<br><br><h3 class='install_heading'>Internet Explorer Security Warning dialog:</h3>\n";
      html_string += "<span class='install_text_proper' >If Internet Explorer displays the Internet Explorer Security Warning window like below, click the 'Install' button. </span><br>\n";
      html_string += "<img src='images/IE_sec_warning_EN.png'></img><br><br>\n";
      html_string += "<h3 class='install_heading' >Nothing happened or I pressed th wrong button:</h3>\n";
      html_string += "<span class='install_text_proper' >If none of these have been displayed, or if you pressed the wrong button, you can simply try to reload this page by pressing F5 or click <a href=''>here</a></span>\n"; 

      document.getElementById('imageHolder').innerHTML = html_string;
      document.getElementById('imageHolder').style.margin = "20px";
      document.getElementById('outerHolder').style.display = 'block';
   } // end catch
} // end detectComponent()


// A very unuseful error display routine. We have never
// been provided with an error number -> meaning mapping.
function ErrorEncountered(){
   var ddc = document.getElementById("LogitechDDC");
   // An error number is not useful to the end user
   //alert( "error encountered: " + ddc.GetErrorCode() );
}


// Start Detection routine - this is actively used in the 
// stand alone page solution we are currently employing, 
// as well as the previously developed embed-it-in-a-loaded-page
// solution. 
function StartDetection(){
   document.getElementById('spinner').style.display = "block";
   var ddc = document.getElementById("LogitechDDC");

   if ( ddc != null ){
 
         if (usingLeaderTech == true){
            ddc.ProductXMLPath = "http://wwwtest.onlineregister.com/logitechreg/plugins/ddc_products.xml";
         }
         else{
            ddc.ProductXMLPath = "http://www.logitech.com/devicedetector/Products/products.xml"
         }
  
      }
      ddc.IncludeGhostDevices = false;
      ddc.VIDFilter = "0x451, 0x46d";
      ddc.IncludeDuplicates = true;
      ddc.IncludeReceivers = true;
      try{
         ddc.StartDetectDevices();
      }
      catch(e){ 
         return;
      }
   }

// Routine used when there is an option to cancel the detection 
// We have no such option in place. 
function StopDetection(){
   document.LogitechDDC.StopDetectDevices();
   document.getElementById("spinner").style.display = "block";
}

// Same as above, with display actions.
function DetectDevicesCancelled(){
   alert("Detection cancelled");
   document.getElementById("spinner").style.display = "none";
}

// This is the current routine for our individual page solution.
function DetectDevicesFinished(){

   var ddc = document.getElementById("LogitechDDC");
   var numDevices = ddc.GetDetectedDeviceCount();

   foundCTIDs = new Array();   
   for ( i = 0; i < numDevices; i++ ){
      var ix = 0;
      var oDevice = new Array();
      oDevice[ix++] = i+1;    //?
      oDevice[ix++] = ddc.GetDetectedDevice( "hpid", i );     // Host Protocol id
      oDevice[ix++] = ddc.GetDetectedDevice( "cAtegory", i ); // Category
      oDevice[ix++] = ddc.GetDetectedDevice( "psid", i );     // PSID
      oDevice[ix++] = ddc.GetDetectedDevice( "cid", i );      // CID
      oDevice[ix++] = ddc.GetDetectedDevice( "productname", i ).replace( /;/g, "<br>"  );     // Product Name
      oDevice[ix++] = ddc.GetDetectedDevice( "codename", i ).replace( /;/g, "<br>"  );        // Code Name
      oDevice[ix++] = ddc.GetDetectedDevice( "Epid", i ).replace( /;/g, "<br>"  );    // enumeration protocol id
      oDevice[ix++] = ddc.GetDetectedDevice( "PartNumber", i ).replace( /;/g, "<br>"  );      // PartNumber
      // This is how sets of matching values can be pulled out
      // depending on the criterial we are looking for. 
      
      var cid = oDevice[ix++] = ddc.GetDetectedDevice( "cid", i );
      if (cid != ""){
         foundCTIDs.push(cid);
      }
   }
 
   var counter = 0; 
   var num_elements = 3; // per row

   var to_print = '   <TABLE border="0" id=\"image_selector_table\" style=\"font-face: Arial,\"Helvetica Neue\",Helvetica,sans-serif ; font-size: 15.2333px; color: #000000\" align=\"left\" border=\"0\">\n      <TR>\n';
 
   for (var pcat in productList){
     for (var whfm in productList[pcat].WHFM){
       for (var whpr in productList[pcat].WHFM[whfm].WHPR){

           // This is the current CTID / CID in our JSON 
           myctid = productList[pcat].WHFM[whfm].WHPR[whpr].CTID;

           // Go through every found CTID and compare it against the current 
           // ctid, if this is too slow, we can likely re-index some JSON in a time/space trade-off 
           for (var item in foundCTIDs){
              // If there is a match
              if (myctid == foundCTIDs[item]){ 
                 foundCTIDs.splice(item, 1);
                 var image_url = productList[pcat].WHFM[whfm].WHPR[whpr].URL;
                 var description = productList[pcat].WHFM[whfm].WHPR[whpr].NAME;
                 // Close the row if we will be creating another row
                 if ((counter != 0) && ((counter % num_elements) == 0)){
                    to_print = to_print + "      </tr>\n";
                    
                    // And create the new row
                    to_print = to_print + "      <tr valign=\"top\">\n";
                 }

                 to_print = to_print + '         <td class="unselected_border" align="center"\n';

                 to_print = to_print + 'onmouseover="this.className=\'selected_border\'; " \n';
                 to_print = to_print + 'onmouseout="this.className=\'unselected_border\'; " \n';
                 
                 to_print = to_print + 'onclick="submitValues(\'' + pcat +'\', \'' + whfm + '\', \'' + whpr + '\');"\n'; 
                 to_print = to_print + '>';

                 to_print = to_print + '<img width="150" height="150" src="';
                 var image_src = '<img src=' + image_url + '>\n'; 
                 if(image_url != ""){
                    to_print = to_print + image_url ;
                 }
                 else{
                    to_print = to_print + 'images/questionMark.jpg';
                 }
                 to_print = to_print + '"><BR><BR> <b style=\'font-size: 11px; font-family: sans-serif;\'>'+ description + '</b> \n\t\t </td>\n';
                 counter++;

              } // end match
           } // end for item in foundCTIDs
       } // end whpr
     } // whfm
   } // pcat
  
   to_print = to_print + '</TABLE>\n';

   document.getElementById('results_holder').style.display = 'block'; 
   document.getElementById('bottom_holder').style.display = 'block';
   document.getElementById('results').innerHTML = to_print; 

   // we want to have different heights for this element, depending on how
   // many products we have to show. Since we are just setting the innerHTML
   // we cannot rely on the rendering engine to do this for us, we need to. 
   if (counter == 0){
      document.getElementById('results').style.height = '40px';
   }

   if (counter > 3){
      document.getElementById('results').style.height = '400px'; 
   }
   
}

// This is an example of how we can use the DDC
// to gain system information about the system we 
// are inspecting for components. Currently, we are not 
// using this, as we haven't discussed a way to opt-in or
// opt-out
function GetSystemEnumString(){
   var e = document.LogitechDDC.SystemEnum();
   switch(e){
      case 1:   return "Windows 95"; 
      case 2:   return "Windows 98"; 
      case 3:   return "Windows 98SE"; 
      case 4:   return "Windows ME"; 
      case 5:   return "Windows NT4"; 
      case 6:   return "Windows 2000"; 
      case 7:   return "Windows XP"; 
      case 8:   return "Windows XP64"; 
      case 9:   return "Windows Vista"; 
      case 10:  return "Windows Vista64"; 
      case 11:  return "Windows 7"; 
      case 12:  return "Windows 7 64-Bit"; 
      default : return "Unknown OS"; 
   }
 }


// Not currently used, but a nice idea
function embedLogitechFlash(input_text, id_num){
      
   // This is absolutely necessary, I probably should even check these for duplicates -- BJS
   if (id_num == null){
      alert('embedLogitechFlash must be called with a id_num');
      return false;   }
   var to_return ='';
      
   if (FlashDetect.versionAtLeast(9)== false){

      to_return = '<h2>' + input_text + '</h2>';
      to_return = to_return.replace("%20", " ");
   }  

   if (FlashDetect.versionAtLeast(9) == true){
      document.getElementById('spinner').style.marginLeft="140px";
            to_return = '<center><span id="span_' + id_num + '" class="flash-replaced sIFR-flash-wrap"><embed id="sIFR_replacement_' + id_num + '" class="sIFR-flash" height="42" width="100%" allowscriptaccess="always" wmode="transparent" name="sIFR_replacement_0" type="application/x-shockwave-flash" src="plugins/gotham-book.swf" pluginspage="http://www.adobe.com/go/getflashplayer" flashvars="id=sIFR_replacement_0&content=';
   
      to_return = to_return + input_text + '&width=690&renderheight=42&link=&target=&size=30&css=.sIFR-root%257Bcolor%253A%2523000000%253Bletter-spacing%253A-1.5%253B%257Da%257Bcolor%253A%2523000000%253Btext-decoration%253Anone%253B%257Da%253Ahover%257Bcolor%253A%2523000000%253B%257D&cursor=default&tunewidth=0&tuneheight=-1&offsetleft=&offsettop=2&fitexactly=false&preventwrap=false&forcesingleline=false&antialiastype=&thickness=&sharpness=&kerning=&gridfittype=pixel&opacity=100&blendmode=&selectable=true&fixhover=true&events=false&version=436"/></span></center>';
   }

  to_return = to_return + '';
  return to_return;
}


