/* This a a Global Variable that MUST be left untouched
 *  */       
var MARKER_COUNT = 0;


// Extend jQuery by adding a disableTextSelect function
$(function(){
  $.extend($.fn.disableTextSelect = function() {
    return this.each(function(){
      if ($.browser.mozilla) { //Firefox
        $(this).css('MozUserSelect','none');
      } else if ($.browser.msie) { //IE
        $(this).bind('selectstart',function() { return false; } );
      } else { //Opera, etc.
        $(this).mousedown(function(){return false;});
      }
    });
  });
});
  

/* Navigation Categories are dynamically displayed
 */
function displayNavCategories() {
        for (var cat in CONFIG_DATA) {
          // This will go away, but if for some reason we need
          // to add a marker on the map that doesnt belong to any category, 
          // it can be added to the "_Special" hash
          if (cat.match(/^_/)) { continue; }

          var regexp = /[^a-z0-9]*/ig 
          var catID = cat;
          catID = catID.replace(regexp, ""); 

          var newCat = document.createElement('img');
          $(newCat).attr('class', 'mapCategory');
          $(newCat).attr('id', catID);
          $('#mapCategories').append(newCat);

          $(document.getElementById(catID)).bind('mouseleave', function() {
                                                                           clearAllHilights(); 
                                                                         });
          $(document.getElementById(catID)).bind('mouseenter', function() {
                                                                           clearAllHilights(); 
                                                                           hilightCategory( $(this).attr('id') ); 
                                                                           showClients( $(this).attr('id') );
                                                                         });
          $(newCat).attr('src',cat);
          $(newCat).css('cursor','pointer');
        }
}

/* Creates Marker in the DOM and Places it on the map
 */
function placeNewMarker( coordObj ) {
        var marker = createMarker( coordObj );

        if (marker !== undefined) {
          if ( $.browser.msie && parseInt($.browser.version) < 8 ) {
            /* MSIE continues to be a steaming pile of crap
             * Without this hack, all map markers would be missaligned.
             * IF YOU EVER TRY TO MOD THIS, KNOW THAT IT IS ALSO DEPENDANT ON THE FONT SIZE
             * SET IN createMarker -- Enjoy Pulling out your hair, sucker!! (whoever you may be)
             */
            if ( parseInt($.browser.version) < 7 ) {
              setMarker( marker, { "left": (coordObj.x - ( parseInt(MARKER_COUNT++ + 1) * 7 ) + 4),  // 0 = X-Offset
                                   "top": (coordObj.y - 10), // 0 = Y-Offset
                                   "visibility": "visible"   // Make it visible
                                 } );
            }
            if ( parseInt($.browser.version) > 6 ) {
              setMarker( marker, { "left": (coordObj.x - ( parseInt(MARKER_COUNT++ + 1) * 6 ) + 4),  // 0 = X-Offset
                                   "top": (coordObj.y - 10), // 0 = Y-Offset
                                   "visibility": "visible"   // Make it visible
                                 } );
            }
          } else {
            /* For all other browser that don't suck 
             */
            setMarker( marker, { "left": (coordObj.x - ( parseInt(MARKER_COUNT++ + 1) * 6 ) + 2),  // 0 = X-Offset
                                 "top": (coordObj.y - 11), // 0 = Y-Offset
                                "visibility": "visible"   // Make it visible
                              } );
          }
        }
}

// Creates a Marker in the DOM and returns the element
// Note: CSS Defaults to { visibility: hidden; }
function createMarker(coordObj) {

        if (coordObj == undefined) { return; }
        if ( $('#' + coordObj.x + '_' + coordObj.y).length != 0) {
          // This Marker Exists, we wont create it again
          return;
        }
 
        // Create DIV
        var newMarker = document.createElement('div');
        $(newMarker).attr('class', 'mapMarker');
        $(newMarker).attr('id', coordObj.x + '_' + coordObj.y);
        $('#map').append(newMarker);

        $(newMarker).html('&#149;'); // This is a bullet (dot), we are using for the map Markers.

        if ( $.browser.msie ) {                     // This is a bullshit compatibility hack for MSIE
          $(newMarker).css('font-size','20px');     //
        }

        $(newMarker).css('cursor', 'pointer');
        /* Make marker white again */
        //  $(newMarker).bind('click', function() { alert( $(this).attr('id') ) } );
        $(newMarker).bind('mouseout', function() { $( '#' + $(this).attr('id') ).animate({color: '#FFFFFF'}, 250); } );
        $(newMarker).bind('mouseover', function(e) { // alert('id: ' + $(this).attr('id')); 
                                         /* make marker orange */
                                         // var coords = $(this).attr('id').split("_");
                                         // var actualX = (coords[0] - ( parseInt(MARKER_COUNT + 1) * 7 ) + 4)  // 0 = X-Offset
                                         // var actualY = (coords[1] - 10);
                                         // //alert('id: ' + $(this).attr('id') + ' actual: ' + actualX +','+actualY);
                                         /* Get mouse pointer coordinates, and only do this stuff if they are spot on to the location of the marker */
                                         $( '#' + $(this).attr('id') ).animate({color: '#febe00'}, 250);
                                         showLogo($(this).attr('id') ); } );

        return newMarker;
}

function showLogo( id ) {

  /* Cleanup */
  $('#mapClientsArea').html('');

  var clientsContainer = document.createElement('img');
  $(clientsContainer).attr('src', 'images/logos/' + id +'.png');
  $('#mapClientsArea').css('padding-top', '10px');
  $('#mapClientsArea').append(clientsContainer);
}


function setMarker( el, attribs ) {

        // Test if we were passed an object or id string
        if (typeof el == 'string') {    // String
          el = '#' + el;
        }

        $(el).css(attribs);


}

function placeAllWhiteMarkers() {
        // Foreach Category
        for (var cat in CONFIG_DATA) {
          // Foreach marker coords
          $.each(CONFIG_DATA[cat]._markers, function(i,coordObj) { 
            placeNewMarker(coordObj); 
          } ); 
        }
}

function clearAllHilights() {
  $('.mapMarker').stop( true, true ); // Abort any animations still running
  $('.mapMarker').animate({color: '#ffffff'}, 500);
}

function hilightCategory( cat ) {
  $('.mapMarker').stop( true, true ); // Abort any animations still running
   
  // Sanitize the incoming cat and the JSON catname 
  var regexp = /[^a-z0-9]*/ig 
  cat = cat.replace(regexp, "");

  for (c in CONFIG_DATA) {
    // Get rid of funky chars
    if ( c.replace(regexp, "") == cat) { 
      $.each(CONFIG_DATA[c]._markers, function(i,v){
        if (v == undefined) { return; }
        $( '#' + v.x +'_'+ v.y ).animate({color: '#febe00'}, 250);
      });
    }
  }

}

function showClients( cat, page ) {

  var COLS = 3;
  var ROWS = 8;
  if (page == undefined) { page = 0; }

  $('#mapClientsArea').html('');
  var clientsContainer = document.createElement('div');
  $(clientsContainer).attr({ "id": 'clientsContainerID', "class": 'clientsContainer' });
  $(clientsContainer).css({ "width": '100%', "height": '270px', "overflow": 'hidden' });
  $('#mapClientsArea').append(clientsContainer);

          var moreImg = document.createElement('img');
          var posx = $(clientsContainer).width() - (52 + 53 + 10)
          $(moreImg).attr({ src: 'images/more.png',
                             id: 'moreImgID' } );
          $(moreImg).css({ visibility: 'hidden', position: 'relative', left: posx ,  cursor: 'pointer' } );
          $(moreImg).click( function() { showClients(cat,page+1) } );
          $(moreImg).disableTextSelect();
          $(clientsContainer).after(moreImg);

          var backImg = document.createElement('img');
          $(backImg).attr({ src: 'images/back.png',
                             id: 'backImgID' } );
          $(backImg).css({ visibility: 'hidden', position: 'relative',  cursor: 'pointer' } );
          $(backImg).click( function() { showClients(cat,page-1) } );
          $(backImg).disableTextSelect();
          $(clientsContainer).after(backImg);


  // Sanitize the incoming cat and the JSON catname 
  var regexp = /[^a-z0-9]*/ig 
  cat = cat.replace(regexp, "");


  for (c in CONFIG_DATA) {
    if ( c.replace(regexp, "") == cat) {


      /* Build a table with COLS & ROWS */
      var rowCount = 0;
      var colCount = 0;
      var newCol;

      var start = (ROWS * COLS * page);

      for (i=start; i <= CONFIG_DATA[c]._clients.length; i++) {
        var v = CONFIG_DATA[c]._clients[i];
        if (v == undefined) { return; }
        if ( (rowCount == ROWS) && (colCount == COLS) ) { return; }

        /* Create new column */
        if ( ( rowCount == ROWS ) || (colCount == 0) ) {
          var newCol = document.createElement('div');
          $(newCol).css({ float: 'left', height: '290px', overflow: 'hidden', width: '33%' });
          $(newCol).attr('class', 'clientInfoCol');
          $(newCol).attr('id', 'clientInfoCol_'+colCount);
          $(clientsContainer).append( newCol );
          colCount++;
          rowCount = 0;
        }

        /* Write the client content to the column */
        $(newCol).append('<p>' + v + '</p>');
        rowCount++;

        /* Place the "more" button */
        if ((rowCount == ROWS) && (colCount == COLS)) {
          $(moreImg).css({ visibility: 'visible' } );
        }
    
        /* Place the "back" button */
        if ( (page > 0) && (colCount == 1) && (rowCount == ROWS) ) {
          $(backImg).css({ visibility: 'visible' } );
        }

      }
    }
  }



}


