function toggleFeatures(evt)
{
  $('.features_container:visible').hide();  
  $('#feature_images > img').each(function() {
    this.src = this.src.replace(/_on/, '');
  });

  this.src = this.src.replace(/-trans.png/, '') + '_on-trans.png';
  $('#'+this.id+'_info').show();
  $('#features_right')[0].scrollUpdate();
}

function toggleRaces(evt)
{
//  $('.races_classes_info_container:visible').hide();
//  $('.menu_img').each(function(f) {
//    this.src = this.src.replace(/_on/, '');
//  });
 
//  this.src = this.src.replace(/-trans.jpg/, '') + '_on-trans.jpg';
  
//  $('#'+this.id+'_info').show();
//  $('#rc_right_inner')[0].scrollUpdate();
}

function toggleRacesMenu(evt)
{
      if($(this).hasClass("CLOSED")){
        $(".races-classes-container").slideUp(500,
          function(){
          $(this).prev(".races-classes-head").addClass("CLOSED");
          });
        $(this).removeClass("CLOSED");
        $(this).next(".races-classes-container").slideDown(500);
      } else {
        $(this).next(".races-classes-container").slideUp(500,
          function(){
          $(this).prev(".races-classes-head").addClass("CLOSED");
          });
      };
}


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://static.alganon.com/img/system4/interface.png", "http://static.alganon.com/img/system4/specialInterface.png");
  setListenersGoogleFix();
  $(fixSafariLabels);
  makeSortable();
  
  // Initialize features and history navigation
  if ($('#index_features').length || $('#index_world-history').length) {
    $('#feature_images > img').bind('click', toggleFeatures);
  }
  
  // Initialize races and deities navigation
  if ($('#index_races-classes').length || $('#index_deities-crusades').length) {
    $('#racesclassesmenu > .races-classes-head').bind('click', toggleRacesMenu);
    $('.menu_img').bind('click', toggleRaces);
  }

  
  
  
  
        // Clicking on the Nav Header
      $(".navHDRBTN").click(
        function(){
          var name = $(this).attr("id");
          var AddClass = name.substring(3, name.length)+"close";          
          
          if($(this).hasClass('SUBCLOSE')){
            $(this).next(".navSUBMENU").next(".navSUBFTR").show();
            $(this).removeClass("SUBCLOSE");
            $(this).removeClass(AddClass);
            $(this).next(".navSUBMENU").slideDown();
          } else {
            $(this).next(".navSUBMENU").slideUp(function(){
              $(this).next(".navSUBFTR").hide();
              $(this).prev(".navHDRBTN").addClass("SUBCLOSE");
              // Change out Navigation Element
              //console.log(AddClass);
              $(this).prev(".navHDRBTN").addClass(AddClass);
              });
            };
        });
          
      // Clicking on the Nav Footer
      $(".navSUBFTR").click(
        function(){
            $(this).prev(".navSUBMENU").slideToggle();
            $(this).slideToggle(
              function(){
                $(this).prev(".navSUBMENU").prev(".navHDRBTN").toggleClass("SUBCLOSE");
              });
        });
          
      // Opens external http in new window
      //$('a[href^="http://"]')
      //    .attr("target", "_blank");
      
      
      // Families Menu
      $(".family_menu").click( 
        function(){
          CLICKED = $(this).attr("id");
          ACT = CLICKED.slice(9);
          $(".familyCARD").hide();
          $("#"+ACT).show();
          $(".family_menu").removeClass("famon");
          $("#"+CLICKED).addClass("famon");
          $("#familiesintro").removeClass("introon");
      });
      
      $(".family-head").click(
        function(){
          $(".family-container").slideToggle();
          $(".family-head").toggleClass("CLOSED");
      });
      
      $(".featuremenu").click(
        function(){
          CLICKED = $(this).attr("id");
          $(".features_container").hide();
          $("#"+CLICKED+"_info").show();
          $(".featuremenu").removeClass("featureon");
          $("#"+CLICKED).addClass("featureon");
      });
      
      $(".rcmenu").click(
        function(){
          CLICKED = $(this).attr("id");
          $(".races_classes_info_container").hide();
          $("#"+CLICKED+"_info").show();
          $(".rcmenu").removeClass("rcon");
          $("#"+CLICKED).addClass("rcon");
      });          
      
      $(".dcmenu").click(
        function(){
          CLICKED = $(this).attr("id");
          $(".races_classes_info_container").hide();
          $("#"+CLICKED+"_info").show();
          $(".dcmenu").removeClass("dcon");
          $("#"+CLICKED).addClass("dcon");
      });
      
      // Intro Menu Add-on
      $("#familiesintro").click( 
        function(){
          $(".familyCARD").hide();
          $("#families").show();
          $(".family_menu").removeClass("famon");
          $("#familiesintro").addClass("introon");
      });     
      
      //POP OUT PAGE
      $(function(){
        $('.mapArdonya').click(function(){
          window.open('/map-ardonya', 'Alganon', 'width=720, height=718, menubar=no, status=no, location=no, toolbar=no, scrollbars=yes');
          return false;
        });
        $('.mapHarraja').click(function(){
          window.open('/map-harraja', 'Alganon', 'width=720, height=718, menubar=no, status=no, location=no, toolbar=no, scrollbars=yes');
          return false;
        });
      });

      //FAQ Page
      $('.FAQbody').hide();
      $('.FAQtitle').click(
        function(){
          $(this).next('.FAQbody').slideToggle();
          $(this).toggleClass('ACTIVE');
        });
      
      $('#FAQOPEN').click(
        function(){
          $('.FAQbody').slideDown();
          $('.FAQtitle').addClass('ACTIVE');
        });
      $('#FAQCLOSE').click(
        function(){
          $('.FAQbody').slideUp();
          $('.FAQtitle').removeClass('ACTIVE');
        });
      
      //Music Page
          // HIDE ALL THEN SHOW FIRST TABLE
      $('.TABTABLE').hide();
      $('.TABSTART').show();
      
      // NAV CONTROLS
      $('#REALMS').click(function(){
          $('.TABTABLE').hide();
          $('#mtREALMS').show();
        });
      $('#LOCATIONS').click(function(){
          $('.TABTABLE').hide();
          $('#mtLOCATIONS').show();
        });
      $('#CULTURE').click(function(){
          $('.TABTABLE').hide();
          $('#mtCULTURE').show();
        });
      $('#MISC').click(function(){
          $('.TABTABLE').hide();
          $('#mtMISC').show();
        });
      
      //POP OUT PLAYER
      $(function(){
        $('.POPPLAYER').click(function(){
          window.open('http://static.alganon.com/mp3s/player.html', 'Alganon Soundtrack','width=400, height=22,menubar=no, status=no, location=no,toolbar=no, scrollbars=no');
          return false;
        });
      });
      
      //PURCHASE PAGE
      $(function(){
    	  $('.featureHeader').click(function(){
    		  $(this).next('.featureBody').toggleClass('open');
    		  $(this).toggleClass('headerOpen');
    	  });
      })
      
      // ADMIN News
      $(function(){
      $('#body').keyup(function(){
        var text = $('#body').val();
        var textLength = text.length;
        $('#charCount').html(textLength);
        //console.log (textLength);
        limitChars('body', 1024, 'charlimitinfo');
        })
      });
      
//      $(function(){
//        var text = $('#body').val();
//        var textLength = text.length;
//        $('#charCount').html(textLength);
//      });

      $("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;");
      
//  COUNTDOWN
    var softLaunch = new Date();
    softLaunch = new Date(2009,12-1,1,00,01,00);
    //softLaunch = new Date(2009,12-1,3,01,00,00);
    $('#defaultCountdown').countdown({until: $.countdown.UTCDate(-8,softLaunch), compact:true, format:'HMS'}); 
      
});

// 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';
}
