$(function() {
    
    $(".validate").submit(function() {
        var counter = 0;
        var first_error = "";
        var form = $(this);
        // find all elements with class name of "required" within all divs with a class of field
        $(this).find("div.field .required").each(function() { 
            // remove any previous warnings and validate based on element type
            $.removeWarning($(this));
            if ( ($(this).is("input")) || ($(this).is("select")) || ($(this).is("textarea")) ) {
                var valid = true;
                var o = $(this).val().replace(/^\s+|\s+$/g, '');

                if ($(this).is(".email")) {
                    // if it's an email address make sure the email is valid using both regular expressions
                    var regExp = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;
                    var regExp2 = /(\s+)|(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/;
                    if ( ( o.search( regExp ) ) == -1 || o.search( regExp2 ) != -1 ) {
                        valid = false;
                    }
                } 
                else if ($(this).is(".select-other") && $(this).val() == "--" && $(this).parent().next().find("input").val().replace( /(^\s+)|(\s+$)/g, '' ).length < 1 ) {
                    $.addWarning($(this).parent().next().find("input"));
                } 
                else if ( ($(this).next().is(".icon-cal")) && (o.replace( /(^\s+)|(\s+$)/g, '' ).length < 1 || o == "mm/dd/yyyy") ) {
                    // if it's a date field
                    valid = false;
                } 
                else if (o.replace( /(^\s+)|(\s+$)/g, '' ).length < 1) {
                    // if not an email address take out funky characters and see if its still blank
                    valid = false;
                }
                // if the data is not valid show warning icon
                if (!valid) {
                    $.addWarning($(this));
                    counter++;
                    if ( first_error == "" ) {
                        first_error = $(this).attr("id");
                    }        
                }
                
            }
            else if ( $(this).is("ul") ) {
                // This is for checkboxes
                $(this).each(function() { 
                    // find all elements w/required class name
                    var valid = false;
                    $(this).find("li").each(function() {
                        // checkboxes in the list
                        var testdis = $(this).children("input");
                        //if not an "other" pair
                        if ( testdis.length == 1 ) {
                            if ( $(testdis).attr("checked") == true ) {
                                valid = true;
                            }
                        }
                        //it is an "other"
                        else {
                            if ( $(testdis[0]).attr("checked") && $(testdis[1]).val().replace( /(^\s+)|(\s+$)/g, '' ).length > 0 ) {
                                valid = true;
                            }
                        }
                    });
                    if(!valid) { 
                        $.addWarning($(this));
                        counter++;
                        if ( first_error == "" ) {
                            first_error = $(this).attr("id");
                        }
                    }
                });            
            }
        });
        if ( counter > 0 ) {
            var error_message = $('#'+first_error).parent().children('label').html().replace(":","");
            error_message = error_message.replace("*","");
            alert( "A valid " + error_message + " is required." );
            $('#'+first_error).focus();
            return false;
        }        
    });

    // Removes the Warning Icon
    jQuery.removeWarning = function(el) {
        // find img elements, if it's present, remove it
        $(el).parents(".field").find("img.validation-error").remove();
    };
    
    // Adds the Warning Icon
    jQuery.addWarning = function(el) {
        var img = "<img />";
        // adds the source and class attributes
        img = $(img).attr("src", "/images/icon-warning.gif").addClass("validation-error");    
        // Add the image after the input field
        // if el is part of checkbox group put it after the first list item
        if( $(el).is("ul") ) {
            $(el).find("li:first").append(img);
        }
        // if not throw it at the end
        else {
            $(el).parent().append(img);
        }
    };
     
    $(document).ready(function(){ 
        $(document).pngFix(); 
		
        if($('#stats tr').length > 2){
            //alert('1');
            $('#stats').tablesorter( {sortList: [[1,0]], widgets: ['zebra'],
       		headers: {1:{sorter:'digit'},5:{sorter:'digit'},6:{sorter:'digit'},7:{sorter:'digit'},8:{sorter:'digit'},9:{sorter:'digit'},10:{sorter:'digit'},11:{sorter:'digit'},12:{ sorter:'digit' }    }});
        }
        if($('#roster tr').length > 2){
            //alert($('#roster tr').length);
            $('#roster').tablesorter( {sortList: [[1,0]], widgets: ['zebra'],headers: {5:{sorter:'digit'}}} );
        }
		
    }); 
       
    $('.alumni-start-season').change(function(){
        var start = $(this);
        var end = $('.alumni-end-season');
        var par = $(this).parents('div.field')
        $.get("ajax/get-alumni-seasons.php",
             {start_season:start.val(),end_season:end.val(),id:$('#alumni_id').val(),pid:$('#player_id').val()},
             function(returned_data)
             {
                par.children('div.seasons-group').html(returned_data);
                set_alumni_season_click();
             });
    });
    $('.alumni-end-season').change(function(){
        var start = $('.alumni-start-season');
        var end = $(this);
        $.get("ajax/get-alumni-seasons.php",
             {start_season:start.val(),end_season:end.val(),id:$('#alumni_id').val(),pid:$('#player_id').val()},
             function(returned_data)
             {
                $('div.seasons-group').html(returned_data);
                set_alumni_season_click();
             });
    });
    
       
    $("div#masthead-home").flash(
        {src:"/flash/homepage-masthead.swf",
         width:896,
         height:280,
         wmode:"transparent",
         quality:"high"},
         {version:"8"},
            function(htmlOptions) { //Use this to specify a query string, take out if not needed.
                htmlOptions.flashvars.configFile = "flash/xml/masthead-config.xml.xml";
                $(this).html($.fn.flash.transform(htmlOptions));
        });
     
    $("div.photos-season-years").each(function(){   
        var display_text = $(this).children('em').html();
        $(this).flash(
            {src:"/flash/years-replace.swf",
             width:42,
             height:175,
             wmode:"transparent",
             quality:"high"},
             {version:"8"},
                function(htmlOptions) { //Use this to specify a query string, take out if not needed.
                    htmlOptions.flashvars.displayText = display_text;
                    $(this).html($.fn.flash.transform(htmlOptions));
        });
    });
        
    $("div#weather-wrapper").each(function() {
        var wrapper = $(this);
        $.get('/includes/weather.php', {}, function(data) {
            wrapper.html(data);
            
            wrapper.pngFix({
                blankgif:'/images/blank.gif'
            }); 
        });
    });
    
    var openFn=function(hash){
            hash.w.show();
            var difference = $(window).width();// - $('#dialog').width();
            difference = difference / 2;
            $('#dialog').css({left:difference,top:$(window).scrollTop()+20});
        };
        var hideFn=function(hash){
            $('#photo-large').attr('src', '');  
            hash.w.hide()
            hash.o.remove();
            $('ul#photo-lightbox-image').remove();
            
        };
        $('.jqModal').click(function() {
        var iStart=$('.jqModal').index(this),
            div = $(this).parents('div.photo'),
            img = this.href,
            subject = $('.photo-title', div).text(),
            photog = $('.photo-photog', div).text();
            
        $('#dialog').load('includes/photo-popup.php', { image: img, title: subject, name: photog }, function(data) {
                                                                                                                            
            $('#dialog').jqm({onHide:hideFn, onShow: openFn}).jqmShow().jqmAddClose($('.jqmClose'));
            
            $('#dialog').pngFix({
                blankgif:'/images/blank.gif'
            }); 
            
            $('.jqmClose').click(function() {
                                    
            })
            
        });
        return false;
    });
    
    $('div.news-long').each(function() {
        $(this).hide();
    });
    $('a.news-toggle').toggle( function(event) {
        event.preventDefault();
		var par = $(this).parents('div.news-item')
        par.children('div.news-long').animate({
			height: 'show'
		}, 'slow');
		$(this).toggleClass('active');
		$(this).children('em').html('Close');
        return false;
    },function(event){ 
        event.preventDefault();
		var par = $(this).parents('div.news-item')
        par.children('div.news-long').animate({
			height: 'hide'
		}, 'slow');
		$(this).toggleClass('active');
		$(this).children('em').html('Read More');
      return false;
    });
    
});

function set_alumni_season_click(){
        $('.season-played').click(function(){
            var par = $(this).parents('tr');
            par.toggleClass('played');
            if($(this).is(':checked')){
                par.children('td').each(function(){
                    $(this).children('select').removeAttr("disabled");
                });  
            }else{
                par.children('td').each(function(){
                    $(this).children('select').attr("disabled", true); 
                });  
            }
        });
    }
