function fixSafariLabels() {
	if ($.browser.safari) {                                                                               //only fix labels for Safari
		$('label').click(function() {                                                                       //add function to all label tags
			var tj = $('#'+$(this).attr('for'));                                                              //get the target specified in for="target"
			var tg = (tj.length == 0) ? $(this).children('input,select,textarea,button').get(0) : tj.get(0);  //if no for="target", target first valid child element
			
			if (tg) {                                                                                         //proceed if we have a target DOM element to work with
				var t = tg.type.toLowerCase();                                                                  //get the target element's type
				if (t == 'radio') tg.checked = true;                                                            //browser handles turning off other options
				else if (t == 'checkbox') tg.checked = !tg.checked;                                             //toggle the checked attribute if a radio or checkbox
				if ((t == 'radio' || t == 'checkbox') && tg.onclick) tg.onclick.call(tg);                       //trigger onclick event if any attached to radio/checkbox
				tg.focus();                                                                                     //move focus to the target element
			}
		});
	}
}

// Fix Google Toolbar yellow input fields
function restoreStyles()
{
  if (event.srcElement.style.backgroundColor != "") {
    event.srcElement.style.backgroundColor = "";
  }
}

function setListenersGoogleFix()
{
  $('input').bind('propertychange', restoreStyles);
  inputList = document.getElementsByTagName("INPUT");
  for (i = 0; i < inputList.length; i++) {
    inputList[i].style.backgroundColor = "";
  }
  
  $('select').bind('propertychange', restoreStyles);
  selectList = document.getElementsByTagName("SELECT");
  for (i = 0; i < selectList.length; i++) {
    selectList[i].style.backgroundColor = "";
  }
}

// Form Validation
function wasValid(element)
{
  element.style.backgroundColor = 'LimeGreen';
}

function wasInvalid(element)
{
  element.style.backgroundColor = 'red';
}

function formIsValid(form, valid, invalid)
{
	var c = form.elements;
	var formName = form.name ? form.name : 'form';
	var rules = Forms[formName];
	var formValidates = true;
	
	for(var key in rules) {
    var element = form[key];
	  var ruleset = rules[key];
	    
	  for(var i in ruleset) {
      var nameParts = ruleset[i].name.split('_');
			var validator = window[nameParts[0]];
			
			for(var j = 1, len = nameParts.length; j < len; j++) {
				validator = validator[nameParts[j]];
			}
	    
	    try {
	      var elementValidates = validator(element.value, ruleset[i].parameters);
	          
	      if (elementValidates) {
	        valid(element);  
	      } else {
	        invalid(element);
	        formValidates = false;
	      }
	    } catch (exception) {
	      continue;
	    }
	  }
	}
		
	return formValidates;
}

function limitChars(textid, limit, infodiv)
{
   var text = $('#'+textid).val(); 
   var textlength = text.length;
   if(textlength > limit)
   {
   $('#' + infodiv).html('You cannot write more then '+limit+' characters!');
    $('#'+textid).val(text.substr(0,limit));
    return false;
   } else {
    $('#' + infodiv).html('You have '+ (limit - textlength) +' characters left.');
    return true;
   }
}

jQuery.preloadImages = function() 
{ 
  for(var i = 0; i<arguments.length; i++) { 
    jQuery("<img>").attr("src", arguments[i]); 
  } 
} 

function makeSortable(){
    $('table.sortable').each(function() {
      var $table = $(this);
      
      var calcMny = function($cell) {
        gold = parseInt($cell.find('.mny_gold').text(), 10);
        silver = parseInt($cell.find('.mny_silver').text(), 10);
        copper = parseInt($cell.find('.mny_copper').text(), 10);
        
        gold = isNaN(gold) ? 0 : gold;
        silver = isNaN(silver) ? 0 : silver;
        copper = isNaN(copper) ? 0 : copper;
        
        retval = copper + (silver * 100) + (gold * 10000);
        
        return isNaN(retval) ? 0 : retval;
      }

      $table.find('th').each(function(column) {
        var findSortKey;

        if ($(this).is('.sort-alpha')) {
          findSortKey = function($cell) {
            return $cell.find('.sort-key').text().toUpperCase() + ' ' + $cell.text().toUpperCase();
          };
        } else if ($(this).is('.sort-numeric')) {
          findSortKey = function($cell) {
            var key = $cell.find('.sort-key').text();
            
            if (key !== '') {
              key = parseFloat(key, 10);
            } else {
              key = parseFloat($cell.text(), 10);
            }
            
            return isNaN(key) ? 0 : key;
          };
        } else if ($(this).is('.sort-coin')) {
          findSortKey = function($cell) {
            return calcMny($cell);
          };
        } else if ($(this).is('.sort-rewards')) {
          findSortKey = function($cell) {
            mny = xp = items = 0;
            
            mny = calcMny($cell);
            xp = parseInt($cell.find('.questXPRewardAmt').text());
            xp = isNaN(xp) ? 0 : xp;
            items = $cell.find('.questItemReward').length * 1000000;
            items = isNaN(items) ? 0 : items;
            return items + mny + xp;
          };
        } else if ($(this).is('.sort-date')) {
          findSortKey = function($cell) {
            return Date.parse('1 ' + $cell.text());
          };
        }

        if (findSortKey) {
          $(this).addClass('clickable').hover(function() {
            $(this).addClass('hover');
          }, function() {
            $(this).removeClass('hover');
          }).click(function() {
            var newDirection = 1;

            if ($(this).is('.sorted-asc')) {
              newDirection = -1;
            }

            rows = $table.find('tbody > tr').get();

            $.each(rows, function(index, row) {
              row.sortKey = findSortKey($(row).children('td').eq(column));
            });

            rows.sort(function(a, b) {
              if (a.sortKey < b.sortKey) {
                return -newDirection;
              }

              if (a.sortKey > b.sortKey) {
                return newDirection;
              }

              return 0;
            });

            $.each(rows, function(index, row) {
              $table.children('tbody').append(row);
              row.sortKey = null;
            });

            $table.find('th').removeClass('sorted-asc').removeClass('sorted-desc');

            var $sortHead = $table.find('th').filter(':nth-child(' + (column + 1) + ')');

            if (newDirection == 1) {
              $sortHead.addClass('sorted-asc');
            } else {
              $sortHead.addClass('sorted-desc');
            }

            $table.find('td').removeClass('sorted').filter(':nth-child(' + (column + 1) + ')').addClass('sorted');
            $table.trigger('repaginate');
          });
        }
      });
    });
  }


// Initialize stuff

$(document).ready(function() {
	$.preloadImages("http://www.alganon.com/img/system5/navIcons.png", "http://www.alganon.com/img/system5/navIcons.png");
  setListenersGoogleFix();
  $(fixSafariLabels);
  makeSortable();
  
  /* Marketing Tracking
   * commented out for now 
  $("a[href*='http://myalganon.com/purchase']:not([href*='"+location.hostname+"'])").attr("onClick","pageTracker._link('http://www.myalganon.com/purchase'); return false;");
  $("a[href*='http://www.myalganon.com/purchase']:not([href*='"+location.hostname+"'])").attr("onClick","pageTracker._link('http://www.myalganon.com/purchase'); return false;");
  $("a[href*='http://myalganon.com']:not([href*='"+location.hostname+"'])").attr("onClick","pageTracker._link('http://www.myalganon.com/'); return false;");
  $("a[href*='http://www.myalganon.com']:not([href*='"+location.hostname+"'])").attr("onClick","pageTracker._link('http://www.myalganon.com/'); return false;");
  */
  /* clickHeader */
  $('.clickHeader').click(function() {
	  $('.paperSub').slideUp();
	  $(this).next('.paperSub').slideDown();
  });
  
});

//POP OUT PAGE
$(function(){
  $('.mapArdonya').click(function(){
    window.open('/index/map-ardonya', 'Alganon', 'width=720, height=718, menubar=no, status=no, location=no, toolbar=no, scrollbars=yes');
    return false;
  });
  $('.mapHarraja').click(function(){
    window.open('/index/map-harraja', 'Alganon', 'width=720, height=718, menubar=no, status=no, location=no, toolbar=no, scrollbars=yes');
    return false;
  });
});


// Toggle Visible 
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';
}



