//  Interested in looking at our code?  Maybe you should work for us !!!

//  If you understand most of what is going on below this message and you have a real passion 
//  for working somewhere which breaks into new opportunites and CAN'T STAND red tape you may 
//  be right for the job.  Drop us an email: info@puntersparadise.com.au

  function popup(mylink, windowname, windowOptions)
  {
    if (! window.focus)return true;
    if (typeof(windowOptions) == 'undefined' || windowOptions == null)
      windowOptions = 'width=780,height=450,scrollbars=yes,resizable=yes';
    var href;
    if (typeof(mylink) == 'string')
       href=mylink;
    else
       href=mylink.href;
    window.open(href, windowname, windowOptions);
    return false;
  }

  var requests = new Array(); // ARRAY OF XML-HTTP REQUESTS
  var requestIndexes = new Array(0); // ARRAY OF XML-HTTP REQUEST INDEXES
  requestIndexes[0] = 1; // FIRST INDEX SET TO 1 MAKING IT AVAILABLE

  

  function getNextAvailableRequestObj(type) 
  {
    if (!type) 
    {
      type = 'html';
    }

    // availableIndex IS THE requestIndexes POSITION THAT GETS PASSED BACK
    // INITIALIZED TO THE LENGTH OF THE ARRAY(LAST POSITION + 1)
    // IN CASE A FREE RESOURCE ISN'T FOUND IN THE LOOP
    var availableIndex = requestIndexes.length;

    // GO THROUGH AVAILABLE requestIndexes VALUES
    for (var i=0; i<requestIndexes.length; i++) 
    {
      // IF IT'S 1 (AVAILABLE), ALLOCATE IT FOR USE AND BREAK
      if (requestIndexes[i] == 1) 
      {
        requestIndexes[i] = 0;
        availableIndex = i;
        break;
      }
    }

    // SET TO 0 SINCE IT'S NOW ALLOCATED FOR USE
    requestIndexes[availableIndex] = 0;

    if (window.ActiveXObject) 
    {
      try 
      {
        requests[availableIndex] = new ActiveXObject("Msxml2.XMLHTTP");
      } 
      catch (e) 
      {
        try 
        {
          requests[availableIndex] = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {}
      }
    } 
    else if (window.XMLHttpRequest) 
    {
      requests[availableIndex] = new XMLHttpRequest();
      if (requests[availableIndex].overrideMimeType) 
      {
        requests[availableIndex].overrideMimeType('text/' + type);
      }
    }
    return (availableIndex);
  }

  function sendAjaxRequest(strURL,query,successCallback, failureCallback) 
  {
      var request = requests[getNextAvailableRequestObj()];

      request.open('POST', strURL, true);
      request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      request.onreadystatechange = function() 
      {
        if (request.readyState == 4) 
        {
          if (request.responseText.length > 0)
          {
            if (request.responseText.substring(0,1) == "1")
            {
              successCallback(request.responseText.substring(2));
            }
            else if (request.responseText.substring(0,1) == "0")
            {
              failureCallback(request.responseText.substring(2));
            }
            else
            {
              failureCallback(request.responseText);
            }
          }
          else
            failureCallback(request.responseText);
        }
      }
      request.send(query);
  }

  function getCheckedValue(radioObj) 
  {
    if(!radioObj)
      return "";
    var radioLength = radioObj.length;
    if(radioLength == undefined)
      if(radioObj.checked)
        return radioObj.value;
      else
        return "";
    for(var i = 0; i < radioLength; i++) {
      if(radioObj[i].checked) {
        return radioObj[i].value;
      }
    }
    return "";
  }

  function addLoadEvent(loadFunction) {
    if ( typeof window.addEventListener != "undefined" )
      window.addEventListener( "load", loadFunction, false );

    // IE 
    else if ( typeof window.attachEvent != "undefined" ) {
      window.attachEvent( "onload", loadFunction );
    }
    else {
      if ( window.onload != null ) {
        var oldOnload = window.onload;
        window.onload = function ( e ) {
          oldOnload( e );
          loadFunction();
        };
      }
      else 
        window.onload = loadFunction;
    }
  }

  function clearOptions(selectId)
  {
    for (var i=(document.getElementById(selectId).options.length-1); i >= 0; i--) 
    {
      document.getElementById(selectId).options[i] = null;
    }
  }
  
  function addOption(selectId, txt, val)
	{
		var objOption = new Option(txt,val);
		document.getElementById(selectId).options.add(objOption);
	}

  function getURLParameter( name )
  {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null )
      return "";
    else
      return results[1];
  }

  function SEO_URL(url)
  {
    var spaceRegExp = /\s+/g;
    return (url.replace(", ","-").replace(",","-").replace(spaceRegExp,"-").replace("&amp;","and").replace("&","and").replace("%","-percent").replace("_","-").replace("$","").replace("!","").replace(".","").replace("'","").replace("/","").replace("?",""));
  }

  function MainHandler()
  {
    this.cacheContainer = new Array();
  }

  MainHandler.prototype.favouritesSummary = function()
  {
    var previouslyLoaded = false;
    for(var i = 0; i < mainPageHandler.cacheContainer.length; i++)
    {
      if (mainPageHandler.cacheContainer[i] == 'favouritesSummary')
      {
        previouslyLoaded = true;
      }
    }
    var userID = $("#userID").val();
    if (!previouslyLoaded)
    {
      mainPageHandler.cacheContainer.push('favouritesSummary');
      $.ajax({ 
          url: '/kingtipping/Profile_FavouritesSummary.php', 
          cache: false, 
          data: "u=" + userID,
          success: function(data) { 
            $('#favouritesSummary').html(data);
          },
          error: function() { 
            $('#favouritesSummary').html('<div class="error">An error occurred while retrieving your favourites.<br/><br/>Please refresh your page and try again.</div>');
          }
      }); 
    }
  }

  MainHandler.prototype.matesSummary = function()
  {
    var previouslyLoaded = false;
    for(var i = 0; i < mainPageHandler.cacheContainer.length; i++)
    {
      if (mainPageHandler.cacheContainer[i] == 'matesSummary')
      {
        previouslyLoaded = true;
      }
    }
    var userID = $("#userID").val();
    if (!previouslyLoaded)
    {
      mainPageHandler.cacheContainer.push('matesSummary');
      $.ajax({ 
          url: '/kingtipping/Profile_MatesSummary.php', 
          cache: false, 
          data: "u=" + userID,
          success: function(data) { 
            $('#matesSummary').html(data);
          },
          error: function() { 
            $('#matesSummary').html('<div class="error">An error occurred while retrieving your mates.<br/><br/>Please refresh your page and try again.</div>');
          }
      }); 
    }
  }

  MainHandler.prototype.referralsSummary = function()
  {
    var previouslyLoaded = false;
    for(var i = 0; i < mainPageHandler.cacheContainer.length; i++)
    {
      if (mainPageHandler.cacheContainer[i] == 'referralsSummary')
      {
        previouslyLoaded = true;
      }
    }
    var userID = $("#userID").val();
    if (!previouslyLoaded)
    {
      mainPageHandler.cacheContainer.push('referralsSummary');
      $.ajax({ 
          url: '/kingtipping/Profile_ReferralsSummary.php', 
          cache: true, 
          data: "u=" + userID,
          success: function(data) { 
            $('#referralsSummary').html(data);
          },
          error: function() { 
            $('#referralsSummary').html('<div class="error">An error occurred while retrieving your list of referrals.<br/><br/>Please refresh your page and try again.</div>');
          }
      }); 
    } 
  }

  MainHandler.prototype.search = function()
  {
    var searchQuery = $("#txtSearch").val();
    var searchType = $("#selSearch").val().toLowerCase();
    window.location = "/search/" + escape(searchType) + '/' + escape(searchQuery)+'/';
  }

  MainHandler.prototype.showLogin = function(message)
  {
    hideBanners();
    var width = 800;
    var height = 270;
    $.blockUI({ 
      centerX: true,
      centerY: true,
      message: $('#loginArea'),
      css: { border: '1px solid #000', width: (''+width+'px'), height: (''+height+'px'), top:  ($(window).height() - height) /2 + 'px', left: ($(window).width() - width) /2 + 'px', backgroundColor: '#fff' } });
    $('#txtUsername').focus();
    $('.blockOverlay').click($.unblockUI);
  }

  Array.prototype.removeItems = function(itemsToRemove) 
  {
    if (!/Array/.test(itemsToRemove.constructor)) 
    {
      itemsToRemove = [ itemsToRemove ];
    }
    var j;
    for (var i = 0; i < itemsToRemove.length; i++) 
    {
      j = 0;
      while (j < this.length) 
      {
        if (this[j] == itemsToRemove[i]) 
          this.splice(j, 1);
        else
          j++;
      }
    }
  }

  function setCookieNoExp(name, value) 
  {
    var cookieExp = new Date();     //set new date object
    cookieExp.setTime(cookieExp.getTime() + (1000 * 60 * 60 * 24 * 365 * 5));  //5 years
    document.cookie = name + "=" + escape(value) + "; path=/; expires=" + cookieExp.toGMTString();
  }

  function hideBanners()
  {
    $('ul', this).css('display', 'inline'); $('.bannerInner').css('display','none'); $(".bettingBannerInner").css('display','none'); $(".flashContent").css('display','none');
  }

  function showBanners()
  {
    $('ul', this).css('display', 'none'); $('.bannerInner').css('display','block'); $(".bettingBannerInner").css('display','block'); $(".flashContent").css('display','block');
  }

  function showPopup(pageTitle,contentURL)
  {
    //Setup a popup frame and dynamically load the content into it\
    hideBanners();
    $.blockUI({ 
            theme:    true, 
            title:    pageTitle, 
            css: { width: '570px', top:  ($(window).height() - 300) /2 + 'px', left: ($(window).width() - 570) /2 + 'px' },
            themedCSS: { width: '570px', top:  ($(window).height() - 300) /2 + 'px', left: ($(window).width() - 570) /2 + 'px' },
            message:  '<div class="ui-dialog-content-inner"><p>Loading...</p></div><div class="ui-dialog-footerbar"><p><input id="btnPostMessage" type="image" src="http://c1.puntersparadise.net/buttons/close.png" width="62" height="28" onclick="closePopup(); return false;"/></p></div>'
        }); 
    //Load the content using an ajax call
    $(".ui-dialog-content-inner").load(contentURL);
    /*$.blockUI({ 
      message: '<div class="popupHeader"><div class="popupHeader">Title</div></div><br/><br/>',
      css: { border: '1px solid #000', , , width: '470px', height: '187px', backgroundColor: '#efefef' } });*/
    $('.blockOverlay').attr('title','Click to cancel').click(closePopup);
  }

  function closePopup()
  {
    $.unblockUI();
    showBanners(); 
  }

  var mainPageHandler = new MainHandler();

  $(document).ready(function() 
  {
		$('li.more').hover(hideBanners,showBanners);
    $('ul.sf-menu').mouseover(mainPageHandler.showMenu);
    if ($('input:text').hint)
		  $('input:text').hint();
    $('#favouritesSummaryLink').mouseover(mainPageHandler.favouritesSummary);
    $('#matesSummaryLink').mouseover(mainPageHandler.matesSummary);
    $('#txtSearch').keyup(function(e) {
      if(e.keyCode == 13) {
        mainPageHandler.search();
      }
    });
    if ($.preloadImages)
    {
      $.preloadImages("/images/loading.gif");
      $.preloadImages("/images/loadingGrey.gif");
    }
    $("#txtTimezoneJS").val((new Date().getTimezoneOffset()/60)*(-1));

    var hideDelay = 500;    
    var currentID;  
    var hideTimer = null;  
    var container = $('<div id="hoverContainer">'  
        + '<table width="" border="0" cellspacing="0" cellpadding="0" align="center" class="hoverPopup">'  
        + '<tr>'  
        + '   <td class="corner topLeft"></td>'  
        + '   <td class="top"></td>'  
        + '   <td class="corner topRight"></td>'  
        + '</tr>'  
        + '<tr>'  
        + '   <td class="left">&nbsp;</td>'  
        + '   <td><div id="hoverContent"></div></td>'  
        + '   <td class="right">&nbsp;</td>'  
        + '</tr>'  
        + '<tr>'  
        + '   <td class="corner bottomLeft">&nbsp;</td>'  
        + '   <td class="bottom">&nbsp;</td>'  
        + '   <td class="corner bottomRight"></td>'  
        + '</tr>'  
        + '</table>'  
        + '</div>');  
     
      $('body').append(container);  
      
      $('.hoverTrigger').live('mouseover', function()  
      {  
        //Hide the banner
        $('.bannerInner').css('display','none');
        var pos = $(this).offset();  
        var width = $(this).width();
        var height = $(this).height();
        container.css({  
            left: (pos.left ) + 'px',  
            top: pos.top + height + 5 + 'px'  
        });  
        if (hideTimer)  
          clearTimeout(hideTimer);  
        // format of 'rel' tag: userid
        if ($(this).attr('rel') != null)
        {
          var settings = $(this).attr('rel').split(',');
          var currentID = settings[0];
          var dateInfo = settings[1];
      
          // If no guid in url rel tag, don't popup blank  
          if (currentID == '')  
              return;  
      
          $('#hoverContent').html('<img src="http://c1.puntersparadise.net/loading.gif" width="16" height="16"/>');  
          
          $.ajax({  
              type: 'GET',  
              url: '/kingtipping/LadderBoardTipDetails.php',  
              data: 'userID=' + currentID + '&date=' + dateInfo,  
              success: function(data)  
              {  
                  // Verify that we're pointed to a page that returned the expected results.  
                  if (data.indexOf('hoverResult') < 0)  
                  {  
                    $('#hoverContent').html('<span >Did not return a valid result for person ' + currentID + '.  Please have your administrator check the error log.</span>');  
                  }  
      
                  // Verify requested person is this person since we could have multiple ajax  
                  // requests out if the server is taking a while.
                  if (data.indexOf(currentID) > 0)  
                  {                    
                    var text = $(data).html();  
                    $('#hoverContent').html(text);  
                  }  
              }  
          });  
      
          container.css('display', 'block');  
        }
        else
        {
          //Non-axax request
          $('#hoverContent').html($(this).children(".popupMessage").html());  
          container.css('display', 'block');  
        }
        
      });  
      
      $('.hoverTrigger').live('mouseout', function()  
      {  
        $('.bannerInner').css('display','block');
        if (hideTimer)  
            clearTimeout(hideTimer);  
        hideTimer = setTimeout(function()  
        {  
          container.css('display', 'none');
        }, hideDelay);  
      });  
      
      // Allow mouse over of details without hiding details  
      $('#hoverContainer').mouseover(function()  
      {  
          if (hideTimer)  
              clearTimeout(hideTimer);  
      });  
      
      // Hide after mouseout  
      $('#hoverContainer').mouseout(function()  
      {  
        $('.bannerInner').css('display','block');
          if (hideTimer)  
              clearTimeout(hideTimer);  
          hideTimer = setTimeout(function()  
          {  
            container.css('display', 'none');
          }, hideDelay);  
      });  

      if ($.facebox)
      {
        $('a[rel*=facebox]').facebox();
        $(document).bind('reveal.facebox', function() { $('.bannerInner').css('display','none'); })
        $(document).bind('close.facebox', function() { $('.bannerInner').css('display','block'); })
      }
  });