var mTimer;


// not used yet -- from http://www.netlobo.com/div_hiding.html
function toggleLayer( whichLayer )
{
  var elem, vis;
  if( document.getElementById ) // this is the way the standards work
    elem = document.getElementById( whichLayer );
  else if( document.all ) // this is the way old msie versions work
      elem = document.all[whichLayer];
  else if( document.layers ) // this is the way nn4 works
    elem = document.layers[whichLayer];
  vis = elem.style;
  // if the style.display value is blank we try to figure it out here
  if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
    vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
  vis.display = (vis.display==''||vis.display=='block')?'none':'block';
}

function render_table( mdata )
{
  // dynamically append a table to the target div
  var iTable =  document.getElementById('ls_listing');
  temp = '<table id="myTable"><colgroup><col id="col1_1"></col><col id="col1_2"></col><col id="col1_3"><col id="col1_4"></col></colgroup><thead><tr><td>&nbsp;</td><td class="ls_table_head" width="180">Title</td><td class="ls_table_head" width="80">Phone</td><td class="ls_table_head">Address</td><td class="ls_table_head">Website</td></tr></thead><tbody>';
  for (ii=0;ii < mdata.listings.length; ii++)
  {
    if (ii % 2 == 0 )
    {
      row_style = 'even';
    } else {
      row_style = 'odd';
    }
    if ( typeof mdata.listings[ii].map_url == 'undefined' ) 
    {
      mdata.listings[ii].map_url = '';
    }
    mdata.listings[ii].address = mdata.listings[ii].address.replace(/,/g, "<br>");
    var js_cust_link = ' onClick="lsSubmit(false, \'/cgi-bin/ls_index.cgi?AJAX=CUST&CMD=AJAX&cat=' + mdata.cat + '&cust=' + mdata.listings[ii].customer_id + '&root=' + mdata.root + '\', \'centrecontent\');return false;"'; 
    //js_cust_link = ''; // TEMP MOD TO FORCE LINKS TO BE RENDERED BY CGI
    temp =temp + '<tr class="' + row_style + '" id="l' + ii +'"><td>' + mdata.listings[ii].map_url + '</td><td>' + '<a href="/cgi-bin/ls_index.cgi?root=' + mdata.root + '&cust=' + mdata.listings[ii].customer_id + '&root=' + mdata.root + '&cat=' + mdata.cat + '" ' + js_cust_link + '>' + mdata.listings[ii].title + '</a></td><td>' + mdata.listings[ii].phone +'</td><td>' + mdata.listings[ii].address + '</td><td>';
    
    
    
    if (mdata.listings[ii].website.length > 5 )
    {
      temp = temp + '<a href="' + mdata.listings[ii].website + '" target="_blank">Link</a></td></tr>';
    } else {
      temp = temp + '</td></tr>';
    }
  }
  if (( typeof mdata.next != 'undefined' )  || (typeof mdata.prev != 'undefined'))
  {
    var prevlink = ' ';
    var nextlink = ' ';
    if ( typeof mdata.next != 'undefined' )
    {
      nextlink = '<a href="#" onclick="lsSubmit(false, \'/cgi-bin/ls_index.cgi?AJAX=CATLIST&CMD=AJAX&cat=' + mdata.cat + '&offset=' + mdata.next + '\',\'centrecontent\');return false;">Next</a>'; //next
    } 
    if ( typeof mdata.prev != 'undefined' )
    {
      prevlink = '<a href="#" onclick="lsSubmit(false, \'/cgi-bin/ls_index.cgi?AJAX=CATLIST&CMD=AJAX&cat=' + mdata.cat + '&offset=' + mdata.prev + '\',\'centrecontent\');return false;">Back</a>'; //next
    }
    
    temp = temp + '<tr><td colspan="3">' + prevlink + '</td><td>' + nextlink + '</td></tr>';
  }
  iTable.innerHTML = temp + '</tbody></table>';
}

//////////// RUN ON LOAD
if (GBrowserIsCompatible()) 
{

  // arrays to hold copies of the markers and html used by the side_bar
  // because the function closure trick doesnt work there
  var gmarkers = [];
  var htmls    = [];
  var i = 0;

  // pin icon mod as per http://www.econym.demon.co.uk/googlemaps/geicons.htm
  var baseIcon              = new GIcon();
  baseIcon.iconSize         = new GSize(32,32);
  baseIcon.shadowSize       = new GSize(56,32);
  baseIcon.iconAnchor       = new GPoint(16,32);
  baseIcon.infoWindowAnchor = new GPoint(16,0);
  var pushpin = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal5/icon14.png", null, "http://maps.google.com/mapfiles/kml/pal5/icon14s.png");
}
    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
}

function createMarker(point,name,html, list_index)
{
  var marker = new GMarker(point, pushpin );
  GEvent.addListener(marker, "click", function() 
  {
    marker.openInfoWindowHtml(html);
  });
  
  GEvent.addListener(marker, "mouseout", function() 
  {
    // change listing background back to default
    selrow = document.getElementById('l'+list_index);
    if ( undefined != selrow  )
    {
      if ( list_index % 2 == 0)
      {
        selrow.className = 'even';
      } else {
        selrow.className = 'odd';
      }
    }
  });
  
  GEvent.addListener(marker, "mouseover", function() {
    // change listing background to selected
    selrow = document.getElementById('l'+list_index);
    if ( undefined != selrow )
    {
      selrow.className = 'row_selected';
    }

  });
  // save the info we need to use later for the side_bar
  gmarkers[i] = marker;
  htmls[i]    = html;
  i++;
  return marker;
}


function myclick(i)
{
        gmarkers[i].openInfoWindowHtml(htmls[i]);
}

//////////// END RUN ON LOAD

function render_map( mdata, latAvg, longAvg )
{
  GUnload();
  // create the map
  if (latAvg != 0)
  {
    var map = new GMap2(document.getElementById("map"));
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.setCenter(new GLatLng(  latAvg, longAvg), 14);
    // add points using mdata object
    for(ii=0;ii < mdata.listings.length; ii++)
    {
      if ( mdata.listings[ii].GIS_lat < 0 ) 
      {
         var point = new GLatLng( mdata.listings[ii].GIS_lat, mdata.listings[ii].GIS_long );
         mdata.listings[ii].map_url = '<a href="javascript:myclick(' + i + ')" style="font-size: 10px;"><img src="http://maps.google.com/mapfiles/kml/pal5/icon14.png" border="0" height="20"></a>';
         var marker = createMarker(point, mdata.listings[ii].title, mdata.listings[ii].title + '<br />' + mdata.listings[ii].address + '<br/>' + mdata.listings[ii].phone + '<br><a href="' + mdata.listings[ii].website + '" target="_blank">' + mdata.listings[ii].website + '</a>', ii);
         map.addOverlay(marker);
      } else {
        mdata.listings[ii].map_url = '';
      }
    }
  } else {
    document.getElementById("map_table").innerHTML = '';
  }
}


function GetCookie( name ) // taken from SAMS Javascript unleashed
{
  var result = null;
  var myCookie = " " + document.cookie + ";";
  var searchName = " " + name + "=";
  var startOfCookie = myCookie.indexOf(searchName);
  var endOfCookie;
  
  if (startOfCookie != -1) {
    startOfCookie += searchName.length;
    endOfCookie    = myCookie.indexOf(";",startOfCookie);
    result         = unescape(myCookie.substring(startOfCookie, endOfCookie));
  }
  return result;
}

function startup()
{
  //load('/cgi-bin/category_json.cgi?CMD=NAV','ls_cat_nav', false); // this should probably be hard coded in the first instance - use olde ls publishing by templtate to do this for each rired version of the file
  document.getElementById('top_select').value = '1';  // prevents browser remembering value
  //testChat();
  if ( window.location.hostname == 'www.localshop.com.au')
  {
           document.title = "Localshop Internet Directory Service";
  } else {
    if ( window.location.hostname == 'localshop')
    {
      //document.logo.src = "/images/logo_localshop.jpg";
      //document.title    = "Development Server";
    } else {
      if ( window.location.hostname == 'wwww.com.au')
      {
         document.title = "wwww.com.au - Who What Where When ";
      } else if (window.location.hostname == '10.0.1.13') {
		 document.title = "Internal Testing";
      } else {
        //alert('You are accessing an unknown domain - google maps will be disabled - try again with www.localshop.com.au to enable google maps');
      }
    }
  }
  
  // handle login logout form creation
  var session_cookie = GetCookie('session_id');
  var loginout = document.getElementById('loginout');
  if (session_cookie.length > 1)
  {
    //if ( session_cookie <> '' )
    loginout.innerHTML = '<!--LOGOUT-->';
  } else {
    loginout.innerHTML = '<!--LOGIN-->';
  }
  //lsSubmit(false,'/cgi-bin/ls_index.cgi?CMD=AJAX&AJAX=CONTENT','centrecontent');
  
}

function select_site(form)
{
  if (form.sitesel.selectedIndex == 0) return;
  load( form.sitesel.options[form.sitesel.selectedIndex].value, 'ls_cat_nav', false);
  // TODO: Load intro page
}

////////////////////////////// START LS PORTAL SUITE INTERFACE CODE
var http_request = false;
function makePOSTRequest(url, parameters) {
   http_request = false;
   if (window.XMLHttpRequest) { // Mozilla, Safari,...
      http_request = new XMLHttpRequest();
      if (http_request.overrideMimeType) {
      	// set type accordingly to anticipated content type
         //http_request.overrideMimeType('text/xml');
         http_request.overrideMimeType('text/html');
      }
   } else if (window.ActiveXObject) { // IE
      try {
         http_request = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
         try {
            http_request = new ActiveXObject("Microsoft.XMLHTTP");
         } catch (e) {}
      }
   }
   if (!http_request) {
      alert('Cannot create XMLHTTP instance');
      return false;
   }
   
   http_request.onreadystatechange = handlePostResponse;
   http_request.open('POST', url, true);
   http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   http_request.setRequestHeader("Content-length", parameters.length);
   // http_request.setRequestHeader("Connection", "close"); // removed as per experience with pscott
   http_request.send(parameters);
}


function render_into_div( response )
{
  if ( (response.html.length>1) && (response.div.length>1) )
  {
    //alert(response.html);
    document.getElementById(response.div).innerHTML = response.html;
  }
  return true;
}

function handlePostResponse()
{
  if(http_request.readyState == 4){
    if (http_request.status == 200) {
      var raw_response = http_request.responseText;
      
      var response = raw_response.parseJSON(); // uses json.js from json.org
      
      //document.getElementById("loginout").innerHTML = response;
      // check whether user is logged in or not
      var loginout = document.getElementById('loginout');
      if ( response.customer_name.length > 1 )
      {
        loginout.innerHTML = '<center>Logged in as <b>"' + response.customer_name + '"</b><br><br><form method="get" action="#" name="loginform" id="loginform"><input type="hidden" name="LOGOUT" value="LOGOUT"><input type="button" name="BUTTON" value="LOGOUT" onClick="lsSubmit(this.form,\'/cgi-bin/ls_index.cgi\',\'loginlogout\');return false;"></form></center>';
      } else {
        loginout.innerHTML = '<form method="get" action="#" name="loginform" id="loginform"><table border=00><tr><td>User:</td><td><input type="text" name="USERNAME" value=""></td></tr><tr><td>Password:</td><td><input type="text" name="PASSWORD" value=""></td></tr><tr><td colspan="2"><input type="submit" name="AJAX" value="LOGIN" onClick="lsSubmit(this.form,\'/cgi-bin/ls_index.cgi\',\'loginout\');return false;"></td></tr></table></form>';
      }
    }
    
    // check if is straight render html into a div type response
    render_into_div( response );
    if  (response.CONTENT == 'template_websites')
    {
      fillup();
    }
    // handle render commands from server
    if (response.CMD.length > 1) {
      if (response.CMD == 'RENDER_LISTING') {  // display list of category contents
        render_listing( response );
      } else if (response.CMD == 'RENDER_CUSTOMER') {
        render_listing( response );
        document.getElementById('ls_listing').innerHTML = '';
      } else if (response.CMD == 'RENDER_EDITORIAL') {
        // TODO: load editorial content describing the new selected portal -- need to write server side code to provide this
        //lsSubmit(false,'/cgi-bin/ls_index.cgi');
        document.getElementById('centrecontent').innerHTML = '';
        document.getElementById('ls_listing').innerHTML = '';
        
        
      } else if (response.CMD == 'HANDLE_CHAT') {
        //clearTimeout( mTimer );
        //alert('new timestamp is ' + response.timestamp );
        // timestamp is last time submitted a query
        var chat_form = document.getElementById('chat_form');
        chat_form.timestamp.value = response.timestamp;
        var chat_out = document.getElementById('chat_scroll');
        chat_out.innerHTML += response.chat_response;
        chat_out.scrollBottom;
        //mTimer = setTimeout('testChat();',5000);
      }
    }
  }
}

function testChat() {
  //clearTimeout( mTimer );
  // sends a keep alive and check for updates 
  var chat_form = document.getElementById('chat_form');
  
  lsSubmit(false,'/cgi-bin/ls_index.cgi?CMD=AJAX&AJAX=CHAT&timestamp=' + chat_form.timestamp.value );
  //mTimer = setTimeout('testChat();',2000);
}

function getForm(fobj) {
  var str = "";
  var ft = "";
  var fv = "";
  var fn = "";
  var els = "";
  //for (i=0; i<fobj.childNodes.length; i++) {
  for(var i = 0;i < fobj.elements.length;i++) {
    els = fobj.elements[i];
    ft = els.title;
    fv = els.value;
    fn = els.name;
    switch(els.type) {
      case "text":
      case "hidden":
      case "password":
      case "textarea":
      // is it a required field?
        str += fn + "=" + encodeURI(fv) + "&";
        if(encodeURI(ft) == "required" && encodeURI(fv).length < 1) {
          alert('"+fn+" is a required field, please complete.');
          els.focus();
          return false;
        }
        //
        break;
    case "checkbox":
    case "radio":
      if(els.checked) str += fn + "=" + encodeURI(fv) + "&";
        break;

    case "select-one":
      str += fn + "=" + els.options[els.selectedIndex].value + "&";
      break;
    } // switch
  } // for
  str = str.substr(0,(str.length - 1));
  return str;
}

function render_listing( response )
{
        latSum  = 0;
        longSum = 0;
        point_count = 0;
        for (ii=0;ii < response.listings.length; ii++)
        {
          if ( response.listings[ii].GIS_lat < 0)
          {
            latSum  += Number(response.listings[ii].GIS_lat);
            longSum += Number(response.listings[ii].GIS_long);
            point_count++;
          }
        }
        if (point_count == 0 )
        {
          point_count = 1;
        }
        latSum  = latSum  / point_count;
        longSum = longSum / point_count;
        // point_count
      	render_map( response, latSum , longSum );
      	render_table( response );  // populates the dhtml sortable table with contents of response object
}

function lsSubmit( fobj, url, busy_div )
{

  document.getElementById('ls_listing').innerHTML = '';
  if (busy_div != '')
  {
    var busy_target = document.getElementById( busy_div );
    if ( busy_target != null ) 
    {
      busy_target.innerHTML = '<center><img src="/images/loading.gif" alt="Loading Content"></center>';
    }
  }
  
  var poststr;
  if (fobj == false)
  {
    poststr += "&CMD=AJAX";
  } else {
    poststr = getForm( fobj );
    poststr += "&CMD=AJAX";
  }
  //alert(fobj + ' as string');
  //alert("poststr = " + poststr);
  makePOSTRequest(url,poststr);
  return false;
}

